Ever wondered how to find the longest path in a binary tree without getting lost in recursion? 🌳 Let’s break it down. Hey everyone! Day 298 of my 365-day coding journey, and today’s challenge was a classic tree problem: LeetCode’s “Diameter of Binary Tree.” This one really tests how well you understand recursion and tree traversal logic. Let’s dive in! ⚡ 🛠️ The Problem Given the root of a binary tree, the goal is to find the length of the tree’s diameter — the longest path between any two nodes. The path may or may not pass through the root. 🎯 The Approach I explored two different solutions to understand both logic and optimization: Solution 1: Brute Force My initial solution used a simple O(n²) approach: 1. For every node, calculate the height of its left and right subtrees. 2. Compute the possible diameter as left_height + right_height. 3. Keep track of the maximum diameter across all nodes. It worked, but recalculating heights multiple times made it inefficient. Solution 2: DFS (Optimized) The optimized O(n) solution uses Depth-First Search to calculate the height and diameter simultaneously. Here’s the key idea: 1. A helper function returns the height of a node (1 + max(left_height, right_height)). 2. While returning, it also updates a variable tracking the max diameter by checking left_height + right_height. This way, a single recursive pass gives both results efficiently — no repeated calculations. 🧠 Key Takeaways - Many tree problems can be optimized by combining calculations in a single DFS traversal. - The brute force approach helps you understand the logic, but recognizing overlapping computations leads to real optimization. - Recursion becomes powerful when you learn how to return one value and update another along the way. 💡 Challenge for you! When solving tree problems, do you prefer starting with a brute-force approach to understand it or jump straight to an optimized one? Let me know below! 💬 📺 Check out my detailed video walkthrough: https://lnkd.in/g9jd55ZK 🔥 Join the Conversation If you’re learning DSA or practicing tree problems, let’s connect! Always great to share ideas and grow together. 🚀 #CodingJourney #365DaysOfCode #LeetCode #DSA #BinaryTree #Trees #Recursion #ProblemSolving #DepthFirstSearch #CodingCommunity #DeveloperLife #LearningEveryDay #TechLearning #Programming
Subbareddy karri’s Post
More Relevant Posts
-
🔁 Ever tried to understand Recursion — but felt like you’re looping forever? Let’s break it down once and for all 👇 --- 🧠 What is Recursion? Recursion is when a function calls itself to solve smaller versions of the same problem — until it reaches a base case. Think of it like standing between two mirrors — the reflection goes deeper and deeper, but there’s always a point where it stops. That stopping point is your base case! --- 💡 Real-World Example: You open a stack of nested boxes. Each box contains another box — until the final one has your gift. To get it, you open the top box (call the function), find another box inside (recursive call), and repeat — until you reach the last box (base case). Then you close each box back as the function returns! --- ⚙️ Simple Code: int factorial(int n) { if (n == 0) return 1; // base case return n * factorial(n - 1); // recursive call } --- 🪄 Why It’s Powerful: Makes complex problems simpler Foundation for divide and conquer algorithms Used in backtracking, tree traversal, dynamic programming, and more --- ⚠️ Quick Tip: Always define your base case properly — otherwise, recursion becomes an infinite loop 🔄 --- 🚀 In short: > “Recursion is thinking smaller to solve bigger.” --- Resources 💡 Resources to Learn Recursion 🎓 Beginner-Friendly Tutorials 1. GeeksforGeeks – Recursion Basics ➜ https://lnkd.in/dAK6p8Hi Covers everything from base case, recursive case, and call stack visualization. 2. Programiz – Learn Recursion in C, C++, Python ➜ https://lnkd.in/d_ZSWQ6m Great for code examples and visualization for beginners. If have any queries comment down 👇 #Recursion #ProgrammingConcepts #DSA #CodeLearning #CProgramming #Developers #LogicBuilding #ComputerScience #TechLearning #LearnByDoing #Sarvastrix #Coding
To view or add a comment, sign in
-
-
Today, I revisited one of my favorite algorithmic challenges: searching in a rotated sorted array — but this time, with duplicates allowed. 🧩 The key challenge? When duplicates appear (like [1,0,1,1,1]), traditional binary search fails to clearly identify which half is sorted. The trick is to handle this uncertainty by shrinking the search space when both ends are equal: if (nums[s] == nums[mid] && nums[mid] == nums[e]) { s++; e--; } This small but smart adjustment ensures the algorithm stays as close to O(log n) as possible, even when duplicates make things messy. 💡 Takeaway: Sometimes in problem-solving — and even in real-world coding — progress isn’t about big leaps, but about small, clever optimizations that make your approach robust in every scenario. #Coding #DSA #ProblemSolving #Cplusplus #LearningJourney #LeetCode #SoftwareEngineering
To view or add a comment, sign in
-
-
What if generating all subsets wasn’t the hard part — but avoiding duplicates was? ⚡ Hey everyone! Day 306 of my 365-day coding journey took me into an interesting combinatorial challenge — LeetCode 90: Subsets II. This problem is a great test of recursion, backtracking, and handling duplicates efficiently. Let’s break it down 🛠️ The Problem Given an integer array that may contain duplicates, the goal is to return all possible subsets (the power set) — but without any duplicate subsets. Example: Input: [1,2,2] Output: [[], [1], [2], [1,2], [1,2,2]] 🎯 The Approaches Solution 1: Brute Force + Set - Generate all possible subsets using recursion or bitmasking. - Store each subset in a set to automatically remove duplicates. - Simple to implement, but storing all combinations before filtering makes it inefficient in terms of both time and memory. Solution 2: Backtracking (Optimized) - Sort the array first to group duplicates. - During recursion, skip duplicate elements at the same decision level. - This avoids generating duplicate subsets altogether, making it clean and efficient. - It’s a perfect example of pruning unnecessary branches in recursion. 🧠 Key Takeaways 💡 Sorting helps manage duplicates effectively in combination problems. ⚙️ Using sets removes duplicates but doesn’t scale well for larger inputs. 🚀 Backtracking with skipping logic is both elegant and optimal — generating only unique subsets. 💬 Challenge for You When solving recursion problems, do you prefer brute force first for clarity or jump straight into optimization? Share your thoughts — I’d love to hear your approach! 💬 📺 Watch My Full Walkthrough I’ve explained both brute force and optimized backtracking solutions step-by-step in my latest video: https://lnkd.in/gAEYMPHu 🔥 Join the Conversation If you’re passionate about DSA and love solving problems that sharpen your logical thinking, let’s connect! Every problem solved is one step closer to mastery. 🚀 #CodingJourney #DSA #LeetCode #Subsets #Backtracking #ProblemSolving #Algorithms #DataStructures #Python #JavaScript #TechLearning #CodeNewbies #DeveloperLife #Programming #365DaysOfCode #LearningEveryDay
To view or add a comment, sign in
-
-
Can a tree stay balanced no matter how deep it grows? 🌳 Let’s find out. Hey everyone! Day 299 of my 365-day coding journey was all about trees — LeetCode’s “Balanced Binary Tree.” This is one of those classic problems that truly tests your grasp of recursion and optimization. Let’s dive in! ⚡ 🛠️ The Problem Given a binary tree, the goal is to determine if it’s height-balanced. A tree is height-balanced if, for every node, the height difference between its left and right subtrees is at most 1. 🎯 The Approach I explored two different ways to solve it — one simple but inefficient, and another optimized and elegant. 1️⃣ Brute Force Approach (Top-Down) - For each node, check if both subtrees are balanced. - Compute heights of left and right subtrees separately. - Simple but inefficient — recalculates heights multiple times. - Time Complexity: O(N²) in the worst case. 2️⃣ Optimized Approach (Bottom-Up using DFS) - A smarter way using Depth-First Search. - Calculate height and balance simultaneously in one traversal. - If any subtree is unbalanced, propagate a signal (like -1) upward to stop further computation. - Time Complexity: O(N) 🧠 Key Takeaways - Optimization often comes from rethinking recursion flow — switching from top-down to bottom-up can save massive computation. - The “return height + status” pattern is powerful for many tree problems. - Always analyze if a recursive function can return multiple useful values to avoid redundant work. 💡 Challenge for You! The optimized solution uses a special return value (like -1) to indicate unbalance. How else could you design this logic? Maybe with a helper class or a tuple? Drop your ideas below! 💬 📺 Watch My Walkthrough I’ve explained both approaches (brute force and optimized DFS) in detail here: https://lnkd.in/gyMuFivt 🔥 Join the Conversation If you’re diving deep into recursion and tree problems, let’s connect! Sharing ideas and patterns like these makes the learning journey even better. 🚀 #CodingJourney #365DaysOfCode #LeetCode #DSA #BinaryTree #TreeTraversal #Recursion #DepthFirstSearch #ProblemSolving #Programming #SoftwareEngineering #CodeNewbies #DeveloperLife #TechLearning #LearningEveryDay
To view or add a comment, sign in
-
-
🚀 Big O Notation — The Language of Algorithm Efficiency! If you’ve ever wondered how to measure how fast or scalable your code is, Big O Notation is your answer. It explains how the runtime of an algorithm grows as your input size increases — a must-know for every developer and computer science student. 💡 Here’s a simple breakdown 👇 🔸 O(1) — Constant Time Fastest! Runtime doesn’t depend on input size. 📘 Example: Accessing an element in an array or hash table. 🔹 O(log n) — Logarithmic Time Grows slowly even as input increases. 📘 Example: Binary search, balanced binary trees. 🔸 O(n) — Linear Time Runtime grows directly with input size. 📘 Example: Finding max/min in an unsorted array. 🔹 O(n log n) — Linearithmic Time Efficient mix of linear and logarithmic. 📘 Example: Merge Sort, Quick Sort (average), Heap Sort. 🔸 O(n²) — Quadratic Time Common in nested loops. 📘 Example: Bubble Sort, Selection Sort, Insertion Sort. 🔹 O(n³) — Cubic Time Heavier — often seen in matrix operations. 📘 Example: Naïve matrix multiplication. 🔸 O(2ⁿ) — Exponential Time Doubles with every extra element — very slow! 📘 Example: Recursive subset sum or traveling salesman problem. 🔹 O(n!) — Factorial Time The slowest growth — factorial explosion! 📘 Example: Generating all permutations. 🔸 O(√n) — Square Root Time Grows proportionally to the square root of input. 📘 Example: Finding primes up to n using the Sieve of Eratosthenes. 📊 In short: From O(1) ➡️ O(n!) — as complexity increases, performance decreases. Understanding these helps you write efficient, scalable, and optimized code. 💻 #BigONotation #DataStructures #Algorithms #Coding #Programming #TechLearning #ComputerScience #SoftwareEngineering #CodeOptimization #Developers #ByteByteGo #LearningNeverStops #ProblemSolving #TechEducation #CodingInterview #CareerInTech #DataScience #MachineLearning #ArtificialIntelligence #Python #Java #JavaScript #SoftwareDevelopment #Engineering #StudyResources #CSFundamentals
To view or add a comment, sign in
-
-
Excited to announce DRS-OSS, our open-source, Llama-based system for Just-In-Time Software Defect Prediction! In large-scale software projects, hundreds of commits land daily, each a potential source of regressions. Just-In-Time Defect Prediction (JIT-DP) is used to assess the risk level of individual commits at submission time. By leveraging JIT-DP, teams can: • Prioritize code reviews and testing on high-risk commits. • Automatically gate or flag risky pull requests before deployment. • Optimize CI/CD resources to focus on what matters most—preventing regressions before they land. DRS-OSS is a deployable AI system for JIT-DP. It achieves state-of-the-art performance (F1 = 0.64, ROC-AUC = 0.895) and delivers real-time, reproducible risk feedback at scale. Beyond raw metrics, our simulations show that gating just the top 30% of risky commits (e.g., during periods of high monetization or production sensitivity) can prevent up to 86.4% of defect-inducing code from landing in production, a significant step toward safer and more cost-effective continuous delivery. Our system uses Llama 3.1 8B as its predictor model, efficiently fine-tuned on the ApacheJIT dataset using parameter-efficient adaptation and CPU offloading (4-bit QLoRA + DeepSpeed ZeRO-3) on a single 20 GB GPU. DRS-LLM integrates directly into developer workflows through: • a FastAPI gateway and LLM microservices for inference, • a React dashboard for manual commit analysis, and • a GitHub App that comments on PRs with risk labels and confidence scores. This project is an open-source replication and extension of the “Moving Faster and Reducing Risk: Using LLMs in Release Deployment” paper originally published by Meta. This collaboration was made possible through the support of Dr. Peter Rigby (Concordia University), and Dr. Audris Mockus (University of Tennessee at Knoxville), whose guidance and feedback were invaluable throughout the research and development process. Explore DRS-OSS: Our Paper: https://lnkd.in/eZkrCWUG Website: https://lnkd.in/edB5yCFA GitHub Bot: https://lnkd.in/epXCMNHz Source Code: https://lnkd.in/eRPRYyar Meta's Paper: https://lnkd.in/erUw95QQ If you’re interested in AI for Software Engineering or agent-based CI/CD systems, we’d love to connect and collaborate! #AI #SoftwareEngineering #DefectPrediction #LLM #MLOps #OpenSource #Research #ConcordiaUniversity #UTK #Meta #DRS
To view or add a comment, sign in
-
Ever felt stuck in a "prerequisite rabbit hole"? 🕳️ You want to take 'Advanced Algorithms', but you need 'Data Structures'. To take 'Data Structures', you need 'Intro to Programming'. To take that, you need... 'How to Open a Terminal'? Welcome to LeetCode 210: Course Schedule II. We've seen its sibling (LC 207), which just asks, "CAN you graduate?" This one is tougher. It demands the exact, step-by-step plan to get your diploma. No "yes/no" answers allowed. It wants the full ordering. My first thought? Just pick a course and start. Bad idea. You quickly end up in a circular dependency, staring at an error message. (e.g., A needs B, and B needs A... 🤯) The truly elegant solution here is Depth-First Search (DFS). Instead of figuring out what to take first (like in BFS), the DFS approach is backwards. It asks, "To finish this course, what must I have already finished?" It's a recursive dive: Pick a course, say 'Advanced Algorithms'. Dive deep. "OK, what are its prereqs? 'Data Structures'." Pause 'Advanced Algos' and dive into 'Data Structures'. "What are its prereqs? 'Intro to Programming'." Pause 'Data Structures' and dive into 'Intro'. 'Intro' has no prereqs. Great! Add it to our final list. We're done with 'Intro', so we pop back up. We can now finish 'Data Structures'. Add it to the list. Pop back up. We can now finish 'Advanced Algorithms'. Add it. The final list is built in reverse finishing order (which is a Topological Sort!). The real magic is how DFS detects impossible schedules. We use a "visited" tracker with 3 states: Unvisited: Haven't touched this course. Visiting: We're currently exploring its prereqs (we're in the rabbit hole). Visited: We've finished this course and all its dependencies. If our recursive dive ever hits a course that's already in the "visiting" state... BAM. We found a cycle. It's impossible. This concept isn't just for classes. It's the logic behind: Build systems compiling files in the right order. Task schedulers managing dependencies. Any system where "this" must happen before "that". As someone who loves exploring graph problems, this one is a special kind of puzzle. I had a blast breaking down the DFS logic, the "graph coloring" (visited states), and the recursive stack. What's your preferred way to tackle these graph problems? DFS or BFS? Let me know why in the comments! #leetcode #computerscience #algorithms #datastructures #coding #programming #softwareengineering #developer #techeducation #graphtheory #topologicalsort #dfs #depthfirstsearch
To view or add a comment, sign in
-
Being “full-stack” is not about having a long tool list. It’s about having the ability to see the whole system as one coherent mental model. .NET teaches how to structure logic. Angular teaches how to shape interaction. Python teaches how to accelerate reasoning. Cloud teaches how to scale trust. Cybersecurity teaches how to protect truth. When all of these fuse — you stop being a “coder”… you become a systems thinker. And that is exactly where modern engineering is heading: – less accidental complexity – more intentional architecture – fewer blind spots – more clarity in data flow The future belongs to engineers who design with strategic awareness — not random trial-and-error. And I choose to build from that altitude — every single day. Hashtags (optimum 4) #FullStackEngineering #CloudArchitecture #SystemDesign #EngineeringMindset
To view or add a comment, sign in
-
Here's me on the second day of my learning challenge by Kactii Pythonistas, ever wished for a shortcut to define clean, data-centric classes? Enter @dataclass – your go-to Python decorator from the dataclasses module! This powerful feature is a game-changer for anyone dealing with data structures, designed to simplify your object definitions. What it does: @dataclass transforms ordinary classes into elegant data containers by automatically generating essential methods like __init__(), __repr__(), and __eq__() based on your class attributes. Say goodbye to repetitive setup code! Why @dataclass is indispensable for your toolkit: * 🚀 Boosts Productivity: Drastically reduces boilerplate. You eliminate the need to manually write common methods like constructors, string representations, or comparison logic. This leads to shorter, cleaner, and less error-prone code, freeing you to focus on core logic. * ✨ Enhances Readability & Structure: By clearly defining data attributes at the top of your class, @dataclass makes the purpose and structure of your classes instantly understandable. It's perfect for data modeling, API responses, configuration objects, and more. Embrace @dataclass to simplify your code, improve maintainability, and elevate your Python projects! 🔔 Hit follow us and feel free to share it so others can learn too! #Learning #EdTech #GenAIAgents #GenAILearning #KactiiAcademy #Kactii
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
Loved how you explained both brute force and optimized DFS so clearly 🌳👏 That “update while returning” insight is gold makes recursion click instantly!