Solved Leetcode 497 - Next Greater Element I Here’s the key insight: Use a monotonic decreasing stack. Traverse from right to left. For each element, remove all smaller elements from the stack. The top of the stack becomes the next greater element. To make it efficient for queries, store the results in a map: number → next greater element This reduces the complexity from O(n²) to O(n). What clicked for me was this: The stack is used for computation, and the map is used for fast retrieval. Once you understand this separation of roles, a whole category of problems becomes easier: Next Greater Element Previous Greater Element Stock Span Daily Temperatures #DataStructures #Algorithms #JavaScript #CodingInterview #LeetCode #ProblemSolving
LeetCode 497: Next Greater Element with Monotonic Stack
More Relevant Posts
-
🚀 Solved: Valid Parentheses (Stack Based Problem) Today I worked on a classic problem that looks simple but tests your core logic 👇 🧠 Problem: Given a string containing only (), {}, [] 👉 Check if the parentheses are valid 💡 Approach I used: Used a stack Push opening brackets For closing brackets: Check top of stack If match → pop Else → invalid ⚙️ Key Insight: 👉 Order matters more than count 👉 Stack helps track the sequence correctly 🔥 What I learned: Importance of stack in real problems Handling edge cases (empty stack, mismatch) Writing clean conditional logic 📌 Time Complexity: O(n) 📌 Space Complexity: O(n) 💬 Have you solved this problem differently? Would love to know your approach! #javascript #cpp #datastructures #algorithms #coding #leetcode #interviewprep
To view or add a comment, sign in
-
-
Sometimes the biggest bottleneck in your code isn't the algorithm itself, but how the language handles memory. 💻 Just crushed a complex query problem with a 100% runtime. To get the execution time this low (389ms), I had to step away from standard JavaScript practices and optimize for the machine: Instead of creating new arrays and triggering heavy GC pauses, I allocated a BigUint64Array exactly once and overwrote it. By combining this with Square Root Decomposition for modular arithmetic, the processing time plummeted. A great reminder that when dealing with large datasets, thinking about memory allocation and data types is just as important as the logic itself. #CodingJourney #JavaScript #DataEngineering #Optimization #LeetCode
To view or add a comment, sign in
-
-
🌞 Day 44 – LeetCode 75 ✅ 547. Number of Provinces Today’s problem was about finding how many connected components (provinces) exist in a graph represented using an adjacency matrix. Approach : I treated the matrix as a graph problem: - Each city = a node - isConnected[i][j] = 1 means there is a connection (edge) So the goal becomes: - Count how many disconnected groups exist. DFS Approach : - Maintain a visited[] array to track visited cities Loop through each city: - If not visited → it means a new province - Run DFS to mark all cities connected to it Complexity : - Time: O(n²) → because we scan adjacency matrix - Space: O(n) → visited array + recursion stack Key Insight : This is a classic Connected Components in Graph problem. Even though it looks like a matrix problem, it’s really: - How many disconnected graphs exist? Once you see that pattern, DFS/BFS becomes very natural. Restarting consistency again — building momentum one graph problem at a time 🚀 #LeetCode75 #Day44 #LeetCode #DSA #JavaScript #Graph #DFS #ConnectedComponents #ProblemSolving #Coding #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
Recently, during a community online meet (“From Aprons to Algorithms”), hosted by Raseena Anwar, we were given a homework challenge based on a Two Sum variation problem. At first glance, it looked simple — but there was a twist 👀 We needed to return the original indices even after sorting the array. I solved it using: 🧠 Sorting + Two Pointers technique 💡 Key idea: preserving index information while sorting This problem was a great reminder that: 👉 It’s not always about new algorithms 👉 Sometimes it’s about preserving the right data in the right way Big thanks to Raseena Anwar for mentoring and guiding us through the session 🙌 Details given in the image👇 Would love to know your approach: 🔹 HashMap (O(n)) 🔹 Two Pointers (O(n log n)) #FromApronstoAlgorithms #DataStructures #Algorithms #ProblemSolving #JavaScript #MERNStack #Coding #LeetCode #WebDevelopment
To view or add a comment, sign in
-
-
Day 07: Cracking the "Non-Divisible Subset" Logic 🧩 Today was a true test of algorithmic thinking. I tackled a problem that looks like a standard array search but is actually a brilliant exercise in Number Theory and Remainder Math. The Challenge: Given a set of numbers, find the maximum size of a subset where the sum of any two numbers is not divisible by K The Strategy (Remainder Frequency): Instead of checking every possible pair (which would be very slow), I focused on remainders . If two numbers sum to a multiple of K, their remainders (r1+r2) must sum to K. const s = [19,10,12,10,24,25,22]; const k = 4; function nonDivisibleSubset(k, s) { let freq = new Array(k).fill(0); // count remainders for (let num of s) { freq[num % k]++; } let count = 0; // remainder 0 case if (freq[0] > 0) count++; // check pairs for (let i = 1; i <= Math.floor(k / 2); i++) { if (i === k - i) { // special case when k is even if (freq[i] > 0) count++; } else { count += Math.max(freq[i], freq[k - i]); } } return count; } console.log(nonDivisibleSubset(k,s)) Key Takeaway: When a problem involves divisibility, don't look at the numbers—look at the remainders. It turns a complex pairing problem into a simple counting one! One full week of coding done. The momentum is real! 🚀 #JavaScript #Algorithms #NumberTheory #100DaysOfCode #CodingChallenge #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 28 / 128 – Coding Challenge Progress Today I worked on the classic "Square Root (x)" problem from LeetCode. 🔍 Problem Summary: Given a non-negative integer x, compute and return its square root rounded down to the nearest integer — without using built-in exponent functions. 💡 Approach I Used: I implemented a Binary Search solution to efficiently find the integer square root. Instead of checking every number, I narrowed down the answer by: Picking a middle value Comparing mid * mid with x Adjusting the search range accordingly ⚡ Why Binary Search? It reduces time complexity from O(n) to O(log n) — making the solution much faster and scalable. 🧠 Key Learning: This problem reinforced how powerful binary search is, even beyond sorted arrays — especially for mathematical computations. 📌 Progress: Day 28 complete, staying consistent and learning something new every day! #128DaysOfCode #CodingChallenge #LeetCode #JavaScript #ProblemSolving #BinarySearch #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Mastering a Classic Algorithm: Balanced Parentheses (Stack – LIFO) Today I revisited a fundamental problem that every Software Engineer should understand: validating balanced parentheses using a stack. Why it matters: This pattern appears in compilers, interpreters, and even real-world applications like expression parsing. Here’s the idea: 👉 Use a stack (LIFO) 👉 Push opening brackets 👉 Pop and match when encountering closing brackets 👉 Ensure the stack is empty at the end Clean and efficient JavaScript implementation 👇 This is a great reminder that mastering data structures like stacks is key to solving real algorithmic problems efficiently. I’m currently building and documenting algorithm patterns here: 🔗 https://lnkd.in/ej4fNeZs #SoftwareEngineering #JavaScript #Algorithms #DataStructures #Coding #LeetCode #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Just Uploaded a New LeetCode Solution! Solved LeetCode #26 – Remove Duplicates from Sorted Array using the Two Pointer Technique in JavaScript. This is a must-know pattern for coding interviews — simple idea, but very powerful when applied correctly. 👉 In this video, I’ve covered: Intuition behind the problem Step-by-step dry run Optimal in-place solution (O(n) time, O(1) space) Clean and easy-to-understand JavaScript code 🔗 Watch here: https://lnkd.in/g-HgkGXQ If you're preparing for coding interviews or strengthening your DSA fundamentals, this one is definitely worth your time. Would love to hear your approach to this problem — drop it in the comments 👇 #leetcode #dsa #codinginterview #javascript #twopointer #programming #softwaredevelopment #coding #developers #learning #jdcodebase
Remove Duplicates from Sorted Array | Optimal Two Pointer Approach 🔥 | LeetCode Explained (JS)
https://www.youtube.com/
To view or add a comment, sign in
-
LeetCode Day 13 : Problem 42 (Trapping Rain Water) Just solved another LeetCode problem. It was "Trapping Rain Water", sounds like a physics problem, right? But here's what I actually learned: The core insight, for any position, the water it can hold is limited by the shorter of the two tallest walls surrounding it. min(maxLeft, maxRight) - height[i]. Once that clicked, the solution wrote itself. My first approach used two extra arrays, one for the tallest bar to the left of each position, one for the right. Three passes total. O(n) time, O(n) space. Clean and readable. Then I learned the O(1) space version using two pointers. Instead of pre-building arrays, move from both ends toward the middle. Whichever side is shorter determines the water level, process that side and move inward. Same result, no extra arrays. The pattern I keep seeing, when you need both left and right context, either do two passes and store results, or use two pointers and process on the fly. Same idea, different tradeoff between readability and space. Thirteen problems in. The two pass and two pointer patterns keep showing up in different forms. The more problems you solve, the more you recognise the shape of the solution before you write a single line. The real lesson? Understand why the brute force works first. The optimal solution is just the brute force with the extra space removed. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
-
🚀 Day 6/100 – #100DaysOfDSA Today’s focus was on searching vs sorting and understanding efficiency differences. 🔹 Problems Solved: 1. Binary Search 2. Bubble Sort 💡 Key Learnings: 👉 Problem 1: Binary Search Works only on sorted arrays Divide the search space into half each time 👉 Approach: Find mid index Compare with target Move left or right accordingly ✅ O(log n) Time Complexity ✅ Very efficient for large datasets 👉 Problem 2: Bubble Sort Most people implement Bubble Sort, but today I learned how to optimize it using an early break condition 🚀 👉 Approach: If no swaps happen in a pass, the array is already sorted — so we can stop early instead of continuing unnecessary iterations. ✅O(n) (Optimized with swap flag) 🔥 What I learned today: Choosing the right algorithm matters more than just solving the problem. Consistency continues 💪 Day 6 done! #100DaysOfCode #DSA #BinarySearch #Sorting #LeetCode #ProblemSolving #CodingJourney #JavaScript #TechGrowth #SoftwareEngineer #LearningInPublic
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