“Why does this traversal not need a stack?” 🧠 Morris Traversal (Inorder) A way to traverse a binary tree using O(1) space. No recursion. No stack. Just smart use of pointers. ⚡ How it works: → If left is NULL → visit, go right → If left exists → find inorder predecessor → Create a temporary link (predecessor → current) → Move left → On return → remove link, visit, go right 💡 Core idea: We don’t use extra space… we reuse NULL pointers as a return path. 🎯 Conclusion: • Same traversal • Zero extra space • Deeper understanding of trees Took me a few dry runs to really get it. Did this concept click for you instantly or after struggle? 👀 #DataStructures #Algorithms #BinaryTree #CodingInterview #SoftwareEngineering #LearnInPublic #ProblemSolving #DeveloperJourney #TechLearning #CodingJourney #DSA #CodeNewbie #Programming #ComputerScience #Coding
Morris Traversal of Binary Tree with O(1) Space
More Relevant Posts
-
📌 We learn stacks as a simple concept: Last In, First Out 👉 That makes it easier to recognize using stack as a pattern for problems such as “Parantheses matching” or “Undo/Redo” But then you come across a problem like Daily Temperatures 🌡️ Why would you even think of using a stack here? 🤷♀️ And more importantly — how? 🤔 That’s where the idea of a “Monotonic stack” comes in. 📌 Instead of using a stack just for insertion order, we use it to maintain a condition. 👉 Elements are kept in a specific order (increasing or decreasing) 👉 The moment that order is violated, we start popping So the stack isn’t just storing elements — it’s helping us eliminate unnecessary comparisons and keep only what’s useful ✔️ And that shift is what makes the solution efficient ⚡ Why this problem captures my interest is because: 👉 Not every problem clearly signals the pattern you need, the real skill is identifying which structure helps you track and optimize information efficiently👍 #softwareengineering #leetcode #algorithms #dsa #stack #coding #programming #problemSolving #computerscience
To view or add a comment, sign in
-
-
Hello Everyone!! 💻 LeetCode #2033 — Minimum Operations to Make a Uni-Value Grid At first, I thought: 👉 Try all possible values 👉 Calculate operations Then I realized something important 👇 🔍 You can only add/subtract by x 👉 So all values must have same remainder Otherwise → impossible ❌ 💡 Game-changing insight: 👉 The best target value is the median Because: 👉 Median minimizes total distance ⚙️ Final Approach: Flatten grid Find median Count operations ⚡ Clean + optimal solution 🧠 Big Lesson: Sometimes the hardest problems… 👉 Are just applications of simple math 🔥 Don’t overcomplicate. Recognize patterns. Have you ever solved a problem using median like this? 🤔 #LeetCode #DSA #Algorithms #Programming #ProblemSolving #Math #Developers #CodingJourney
To view or add a comment, sign in
-
-
Mastering array manipulation is fundamental for any developer. The seemingly simple task of finding the largest element in an array presents an excellent opportunity to optimize for efficiency. While sorting the array (O(n log n) time complexity) is one approach, a more performant solution involves a single traversal. By initializing a 'max' variable and iterating once through the array, we can find the largest element in optimal O(n) time and O(1) space. This highlights the importance of choosing the right algorithm for the job. Dive deeper into the implementation details and critical ideas to think about: https://lnkd.in/eBQGgE5w #DSA #Algorithms #DataStructures #Programming #Coding
To view or add a comment, sign in
-
Recover the Tree ?? by providing water! Approach (Recover BST) Do inorder traversal (BST should be sorted) Track previous node If order breaks (prev > current), it’s a violation First violation: first = prev middle = current Second violation (if exists): last = current Time Complexity: O(n) → you traverse all nodes once using inorder Space Complexity: O(h) → recursion stack (h = height of tree) Worst case (skewed tree): O(n) Best case (balanced tree): O(log n) #LeetCode #DSA #DataStructures #Algorithms #Coding #Programming #binarysearchtree
To view or add a comment, sign in
-
-
🚀 Think Anywhere in Code Generation Coding with large language models is tricky because the hardest parts often surface midway—when edge cases or final return logic appear. Traditional reasoning LLMs think first and then write, but this can leave gaps in handling unexpected complexity. This new research paper introduces Think-Anywhere: a method where models can pause and reason at any token position during code generation. These reasoning steps are stripped out afterward, leaving clean, executable code. Key highlights: Trained using cold-start SFT + execution-based RL Outperforms CoT, self-planning, interleaved thinking, GRPO, and recent code post-training techniques Enables models to think exactly where uncertainty arises 📄 Paper: https://lnkd.in/gRfVz57D #MachineLearning #CodeGeneration #LLM #AIResearch #DeepLearning #ReinforcementLearning #Programming #ArtificialIntelligence
To view or add a comment, sign in
-
-
Day 65 on LeetCode Sort Characters By Frequency 🔤📊✅ Today’s problem focused on combining hash maps with custom sorting. 🔹 Approach Used in My Solution The goal was to sort characters in a string based on their frequency in descending order. Key idea in the solution: • Use a hash map to count frequency of each character • Store (character, frequency) pairs in a vector • Apply custom sorting based on frequency (descending order) • Build the result string by repeating characters according to their frequency This approach efficiently organizes characters by importance (frequency). ⚡ Complexity: • Time Complexity: O(n log n) (due to sorting) • Space Complexity: O(n) 💡 Key Takeaways: • Practiced frequency counting using hash maps • Learned how to apply custom comparators in sorting • Reinforced building results based on frequency-driven logic #LeetCode #DSA #Algorithms #DataStructures #HashMap #Sorting #Strings #ProblemSolving #Coding #Programming #Cpp #STL #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity #SoftwareDeveloper #EngineeringJourney
To view or add a comment, sign in
-
-
Vector indexes don't have to break the bank. This video breaks down DiskBBQ — a disk-first vector index that keeps large embedding collections on disk, minimizes RAM usage, and preserves query performance so your vector DB costs don't scale linearly with size. Short, practical explainer with architecture highlights and benchmarks. Read more: https://lnkd.in/efQhhz7F #programming #ai #database https://lnkd.in/eG-yVXbg
Vector Indexes Explained: Big vectors, small RAM - DiskBBQ #programming #ai #database
https://www.youtube.com/
To view or add a comment, sign in
-
Day 72 on LeetCode Search a 2D Matrix 🔍📊✅ Today’s problem was a great application of Binary Search in 2D, breaking it down into two efficient steps. 🔹 Approach Used in My Solution The goal was to determine whether a target exists in a sorted 2D matrix. Key idea in the solution: • First, apply binary search on rows to find the potential row where the target could exist – Check if target lies between matrix[mid][0] and matrix[mid][cols-1] • Once the correct row is found, apply binary search within that row • Return true if found, otherwise false This avoids scanning the entire matrix and ensures efficiency. 🔹 Why This Works Because: • Each row is sorted • The first element of each row is greater than the last of the previous row So we can treat it like a two-level binary search problem. ⚡ Complexity: • Time Complexity: O(log m + log n) • Space Complexity: O(1) 💡 Key Takeaways: • Learned how to extend binary search to 2D structures • Practiced breaking problems into smaller searchable spaces • Reinforced thinking in terms of hierarchical searching 🔥 Another solid step in mastering binary search patterns! #LeetCode #DSA #Algorithms #DataStructures #BinarySearch #Matrix #2DArray #ProblemSolving #Coding #Programming #Cpp #STL #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity #SoftwareDeveloper #EngineeringJourney
To view or add a comment, sign in
-
-
Solved the Reverse Integer problem without using any built-in functions 💻 Implemented a digit-by-digit reversal approach while carefully handling overflow using boundary checks. This ensures the solution is both safe and efficient. 🔹 Time Complexity: O(log n) 🔹 Space Complexity: O(1) Glad to see it pass all test cases with optimal performance 🚀 Sometimes, sticking to fundamentals is the best way to strengthen problem-solving skills. #Coding #DataStructures #Algorithms #ProblemSolving #CProgramming #LeetCode
To view or add a comment, sign in
-
-
Solved a great DP problem today: Count Binary Strings Without Consecutive 1’s. Given a length n, the task is to count all distinct binary strings such that no two 1s are adjacent. Example: n = 3 → 000, 001, 010, 100, 101 → 5 n = 2 → 00, 01, 10 → 3 The key insight: 1. Strings ending with 0 can be formed by appending 0 to all valid strings of previous length. 2. Strings ending with 1 can only be formed by appending 1 to strings that previously ended with 0. This leads to a simple DP relation: 1. zero[i] = zero[i-1] + one[i-1] 2. one[i] = zero[i-1] So the pattern follows a Fibonacci-style sequence, and the problem can be solved in: O(n) time and O(1) space I enjoy how problems like this look simple at first, but the right state definition makes them very elegant. #DataStructures #Algorithms #DynamicProgramming #Coding #ProblemSolving #Cpp #Programming #SoftwareDevelopment
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