Day 38 of #75DaysofLeetCode 🚀 Cracked LeetCode 236 – Lowest Common Ancestor of a Binary Tree! Understanding trees becomes powerful when you master problems like LCA 🌳 💡 Problem Insight: Given a binary tree, find the lowest node that has both p and q as descendants. 🔍 Key Idea: Instead of storing paths, we can solve this using a simple recursive DFS: If current node is null, p, or q → return it Search left and right subtree If both sides return non-null → 🎯 current node is the LCA Otherwise → return the non-null side ⚡ Why this works? Because the first node where both p and q appear in different subtrees is their lowest common ancestor. ⏱ Complexity: Time: O(N) Space: O(H) 📌 Takeaway: You don’t always need extra data structures—smart recursion can simplify complex tree problems! #LeetCode #DataStructures #Java #CodingInterview #BinaryTree #DFS #TechJourney
LeetCode 236: Lowest Common Ancestor of a Binary Tree
More Relevant Posts
-
Day 115 - LeetCode Journey Solved LeetCode 236 – Lowest Common Ancestor of a Binary Tree ✅ This problem revolves around identifying the lowest common ancestor (LCA) of two given nodes in a binary tree. The LCA is defined as the lowest node in the tree that has both nodes as descendants (a node can be a descendant of itself). Approach: I used a recursive depth-first search (DFS) approach to efficiently locate the LCA. The idea is simple but powerful: • If the current node is null, return null • If the current node matches either of the target nodes (p or q), return the node • Recursively search in the left and right subtrees After recursion: • If both left and right calls return non-null values, the current node is the LCA • If only one side returns non-null, propagate that result upward This works because the first node where both targets split into different subtrees becomes the lowest common ancestor. Complexity Analysis: • Time Complexity: O(n), as we traverse each node once • Space Complexity: O(h), where h is the height of the tree (recursion stack) Key Takeaways: • Tree problems often rely on recursive decomposition 🌳 • Returning meaningful values from recursion simplifies logic • LCA is a classic concept frequently asked in interviews All test cases passed successfully 🎯 #LeetCode #DSA #BinaryTree #Recursion #Java #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
Day 25 of my #30DayCodeChallenge: The Art of Categorization! The Problem: Group Anagrams. Given an array of strings, group the words that are rearrangements of each other. The Logic: This problem is a perfect example of using Hashing and Canonical Forms to organize unstructured data efficiently. 1. Identifying the "Signature": The core challenge is realizing that all anagrams, when sorted alphabetically, become the exact same string. I used this "sorted version" as a unique key (the signature) for each group. 2. The Hash Map Strategy: I utilized a HashMap<String, List<String>>. Key: The sorted version of the word. Value: A list of all original words that match that sorted key. 3. Efficient Lookups: Using computeIfAbsent, I streamlined the process of initializing lists and adding words in a single pass. This keeps the code clean and the logic tight. Complexity Analysis: Time Complexity: O(N Klog K), where N is the number of strings and K is the maximum length of a string (due to sorting). Space Complexity: O(N K) to store the grouped strings in our map. One step closer to mastery. Onward to Day 26! #Java #Algorithms #DataStructures #Hashing #ProblemSolving #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 8/100 — #100DaysOfLeetCode Another day, another concept unlocked 💻🔥 ✅ Problem Solved: 🔹 LeetCode 73 — Set Matrix Zeroes 💡 Problem Idea: If any element in a matrix is 0, its entire row and column must be converted to 0 — and the challenge is to do this in-place without using extra space. 🧠 Algorithm & Tricks Learned: Instead of using extra arrays, we can use the first row and first column as markers. First pass → mark rows and columns that should become zero. Second pass → update the matrix based on those markers. Carefully handle the first row and first column separately to avoid losing information. ⚡ Key Insight: The matrix itself can act as storage, reducing extra memory usage. 📊 Complexity Analysis: Time Complexity: O(m × n) → traverse matrix twice Space Complexity: O(1) → solved in-place without extra data structures This problem taught me how small optimizations can significantly improve space efficiency. Learning to think beyond brute force every day 🚀 #100DaysOfLeetCode #LeetCode #DSA #MatrixProblems #Algorithms #Java #ProblemSolving #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 36 of #100DaysOfCode Today I solved LeetCode 155 – Min Stack 💻 🔍 Problem Summary: Design a stack that supports push, pop, top, and retrieving the minimum element — all in constant time O(1). 🧠 Key Learning: This problem teaches how to optimize operations using an auxiliary stack to track the minimum element efficiently. 💡 Approach: Use two stacks: Main stack → stores all elements Min stack → keeps track of minimum values While pushing: Push element to main stack Push to min stack only if it’s smaller or equal While popping: Remove from min stack if it matches top of main stack 📊 Complexity: Time: O(1) for all operations Space: O(n) 🔥 Takeaway: Using extra space smartly can drastically improve performance. This is a great example of designing efficient data structures. #LeetCode #Java #Stack #DataStructures #Algorithms #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Solved LeetCode 2515 – Shortest Distance to Target String in a Circular Array Today I tackled an interesting problem that highlights the importance of handling circular data structures efficiently. 🔍 Problem Insight: Given a circular array of words, a target string, and a starting index, the goal is to find the minimum number of steps required to reach the target by moving either left or right. 💡 Key Learnings: Circular arrays require thinking beyond linear traversal Always consider both directions (forward & backward) Optimizing distance using min(distance, n - distance) is the key trick Simple logic + correct observation = optimal solution ⚙️ Approach Used: Traverse the array to find all occurrences of the target Calculate distance from the starting index Take the minimum considering circular movement 📈 Complexity: Efficient O(n) solution with constant space 🔥 Takeaway: This problem reinforced how small tweaks (like circular behavior) can change the entire approach. A great example of combining logic + observation for clean and optimal solutions. #LeetCode #Algorithms #ProblemSolving #CodingJourney #Java #DataStructures #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 100 Days of Code Day-25 LeetCode Problem Solved: Reverse Nodes in k-Group I recently worked on a Linked List problem that focuses on reversing nodes in groups of size k while preserving the remaining structure if the group size is less than k. 🔹 Strengthened my understanding of pointer manipulation 🔹 Improved problem decomposition skills 🔹 Practiced recursive thinking for efficient implementation 💡 Key takeaway: Breaking complex problems into smaller, manageable parts significantly simplifies the solution approach. Continuing to build consistency in problem-solving and deepen my understanding of Data Structures & Algorithms. #LeetCode #DataStructures #Algorithms #Java #ProblemSolving #SoftwareDevelopment
To view or add a comment, sign in
-
-
Day 23 of my #30DayCodeChallenge: The Art of Pruning! The Problem: Permutations II. Generating all unique permutations of a collection that contains duplicates. The challenge isn't just finding the arrangements, but ensuring we don't repeat work or results. The Logic: This problem is a deep dive into Backtracking with a strategic Pruning layer: 1. The Frequency/State Tracking: Since we have duplicate numbers, we can't just rely on the values themselves. I used a vis [] (visited) boolean array to keep track of which specific index in the array is currently being used in our recursion tree. 2. Sorting for Symmetry Breaking: Before starting the recursion, sorting the array is the secret sauce. By grouping identical numbers together, we can easily identify when we are about to make a "dur"-ate choice." 3. Backtracking: Standard push, recurse, and pop. We explore every valid path, then "undo" our choice by setting vis [j] = false to backtrack and try the next possibility. One step closer to mastery. The logic is getting sharper! Onward to Day 24! #Java #Algorithms #DataStructures #Backtracking #LeetCode #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 80/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Convert Sorted Array to Binary Search Tree A classic divide-and-conquer problem that builds intuition for balanced trees. Problem idea: Convert a sorted array into a height-balanced BST. Key idea: Recursion + choosing the middle element as root. Why? • The array is already sorted • Picking the middle ensures balance • Left half forms left subtree, right half forms right subtree How it works: • Find the middle index of the array • Create a node with that value • Recursively build left subtree using left half • Recursively build right subtree using right half Time Complexity: O(n) Space Complexity: O(log n) (recursion stack) Big takeaway: Whenever you need a balanced BST from sorted data, think divide & conquer with mid as root. 🔥 This pattern is widely used in tree construction problems. Day 80 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #BinarySearchTree #DivideAndConquer #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 39 of My LeetCode Journey 📌 Solved: LeetCode 1848 – Minimum Distance to the Target Element Today’s problem was simple yet a great exercise in improving logical thinking and iteration skills. 🔍 Problem Insight: Given an array, a target value, and a starting index, the goal is to find the minimum distance between the start index and any index where the target exists. 💡 Approach: Traverse the array Check for elements equal to the target Compute distance using |i - start| Keep track of the minimum value ⚡ Key Learning: Sometimes, the most optimal solution is a straightforward linear scan. Don’t overcomplicate when a simple approach works efficiently! ⏱ Complexity: Time: O(n) Space: O(1) 🔥 Consistency is key! Every day, one step closer to mastering Data Structures & Algorithms. #Day39 #LeetCode #Java #DSA #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
#100DaysOfCode | Day 2 of my LeetCode challenge. Today’s problem: 1365. How Many Numbers Are Smaller Than the Current Number. While the problem seems simple, it’s a perfect example of how choosing the right data structure can drastically change performance. Here is how I broke it down: 1. The Brute Force Approach The most simple and easy way is to use nested loops to compare every number with every other number. Logic: For each element, loop through the entire array and count smaller values. Time Complexity: O(N^2) Space Complexity: O(N) (to store the result) 2. The Sorting + HashMap Approach A more scalable way is to sort the numbers. In a sorted array, a number's index is equal to the count of numbers smaller than it. Logic: Clone the array, sort it, and store the first occurrence of each number in a HashMap. Time Complexity: O(N log N) (due to sorting) Space Complexity: O(N) (to store the map) Use - Works for any range of numbers (including very large or negative ones). 3. The Frequency Array (Counting Sort Logic) Since the problem constraints were small (0 to 100), this is the most optimized solution. Logic: Count the frequency of each number using an array of size 101, then calculate a running prefix sum. Time Complexity: O(N) (Linear time) Space Complexity: O(1) (The frequency array size is constant) #LeetCode #100DaysOfCode #Java #SoftwareEngineering #DataStructures #Algorithms
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