🚀 Day 93 of My #100DaysOfCode Challenge! Today, I explored one of the most fundamental and elegant problems in Binary Trees — the Diameter of a Binary Tree 🌳 using C++. The goal of this problem is to find the longest path between any two nodes in a binary tree. This path may or may not pass through the root. To solve it efficiently, I used recursion and the concept of tree height. 💡 What I Learned: 🔹 Height Function: The height of a node is 1 + max(height(left), height(right)). I built a recursive function height(TreeNode* root) that returns the height of any subtree. 🔹 Diameter Function: For each node, I calculated three possible diameters: Diameter of the left subtree Diameter of the right subtree Diameter passing through the current node (left height + right height) The maximum of these three gives the current diameter. 🔹 Key Insight: This approach uses recursion twice (once for height and once for diameter), which makes it O(N²) — a good starting point for understanding the logic before optimizing it to O(N) with a single traversal. 🧠 Concepts Strengthened: Recursive Tree Traversal Depth & Height calculation Problem decomposition using subproblems Understanding tree structure visualization 🌱 Slowly mastering trees — one recursive function at a time! Next step: Optimize the diameter function for O(N) time complexity using a single DFS call. #Day93 #100DaysOfCode #CPlusPlus #DSA #BinaryTree #Recursion #ProblemSolving #CodingJourney #LeetCode
Solved Binary Tree Diameter Problem in C++ with Recursion
More Relevant Posts
-
🚀 LeetCode Challenge Complete! Just solved "Increment Submatrices by One" - a perfect demonstration of the difference array technique for efficient range updates! 💡 Solution Approach: ✅ Phase 1 - Mark boundaries: For each query, add +1 at start column, -1 after end column ✅ Phase 2 - Prefix sum: Accumulate row-wise to get final values ✅ Optimization: Instead of updating entire submatrix, just mark endpoints! The key insight: This is the classic difference array pattern! Instead of incrementing every cell in a range, we mark the boundaries: - Add +1 at the start of the range - Add -1 just after the end of the range - Then do prefix sum to "materialize" the actual values Why it works: Without optimization: Update every cell in [c1, c2] for rows [r1, r2] → O(rows × cols) per query With difference array: Mark 2 positions per row → O(rows) per query Final prefix sum: O(n²) once at the end Example: Range [1,2] in row 0 - Before prefix: [0, +1, 0, -1, 0] - After prefix: [0, 1, 1, 0, 0] ✓ Time: O(q×n×n) → O(q×n + n²) | Space: O(n²) #LeetCode #DifferenceArray #CPlusPlus #Algorithms #SoftwareEngineering #ProblemSolving #RangeUpdate #Optimization
To view or add a comment, sign in
-
-
✨ Day 49 of 50 Days Challenge ✨ Solved LeetCode 115: Distinct Subsequences (Hard) 👉 Problem Statement: Given two strings s and t, return the number of distinct subsequences of s which equal t. 📌 Example: Input: s = "rabbbit", t = "rabbit" Output: 3 Explanation: There are 3 ways to form "rabbit" from "rabbbit" 🔎 Approach Used: ➡️ Dynamic Programming 1️⃣ Create DP table with dimensions [s.length()+1][t.length()+1] 2️⃣ Initialize base cases (empty string matches) 3️⃣ If characters match, sum of (excluding both + excluding s char) 4️⃣ If characters don't match, take value from excluding s char ✅ Complexity Analysis: Time Complexity: O(m × n) — where m = s.length(), n = t.length() Space Complexity: O(m × n) — for DP table (can be optimized to O(n)) 🕒 Result: ✔️ Runtime: 23 ms (Beats 76.75%) ✔️ Memory: 26.98 MB (Beats 62.13%) #LeetCode #Day49 #50DaysChallenge #HardProblem #DynamicProgramming #String #Subsequences #CPlusPlus #DSA #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
✅ Day 4/75 🌟 Today’s Progress 1️⃣ Longest Consecutive Sequence — LeetCode Medium Problem: Given an unsorted array of integers, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. 🔹Approaches: 1️⃣ Sorting Approach (Brute Force) Sorted the array and count the consecutive elements. Time Complexity: O(N log N). 2️⃣ Optimal – HashSet Stored all the numbers in a HashSet. For each number, checked if it’s the start of a sequence (i.e., num - 1 not in set). Then counted how long the consecutive sequence continues. ✅ Time: O(N) | Space: O(N) 2️⃣ Product of Array Except Self — LeetCode Medium Problem: Given an array nums, return an array answer such that answer[i] equals the product of all elements except nums[i], without using division, in O(n) time. 🔹Approaches: 1️⃣ Brute Force: Multiplied all elements except self for each index. ⏱️ Time: O(N²) 2️⃣ Optimal – Prefix & Suffix Product First pass: calculated the prefix products (product of all elements to the left). Second pass: multiplied each element by the suffix product (product of all elements to the right). ✅ Time: O(N) | Space: O(1) (excluding output array) On to Day 5 tomorrow! ✨ #NeetCode #Blind75 #DSA #LeetCode #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
Day 22 of #100DaysOfCode Today I solved the “Permutation in String” problem on LeetCode — a tricky one that really sharpens your understanding of sliding window and frequency mapping in strings. 🧩 Problem in short: Given two strings s1 and s2, the task is to check if any permutation of s1 exists as a substring in s2. At first glance, it feels like a brute-force problem — generate all permutations of s1 and check each in s2. But that’s computational suicide for longer strings. So the challenge was to find a smarter, optimized approach. ⚙️ Intuitive Approach: Instead of generating permutations, I focused on character frequencies. Maintain two frequency arrays — one for s1 and one for the current window of s2. Slide the window across s2, adding and removing characters as you move. Whenever both frequency arrays match, it means that substring of s2 is a permutation of s1. This approach reduces the complexity drastically and relies on pattern recognition through frequency matching, not brute force. Every day in this challenge is a reminder that optimization isn’t about doing less work — it’s about doing the right work. #LeetCode #C++ #ProblemSolving #DSA #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
✨ Day 49 of 50 Days Challenge ✨ Solved LeetCode 115: Distinct Subsequences (Hard) 👉 Problem Statement: Given two strings s and t, return the number of distinct subsequences of s that equal t. A subsequence is formed by deleting some (or none) characters without changing the relative order of the remaining characters. 📌 Examples: Input: s = "rabbbit", t = "rabbit" Output: 3 There are 3 ways to form “rabbit” from “rabbbit”. Input: s = "babgbag", t = "bag" Output: 5 There are 5 ways to form “bag” from “babgbag”. 🔎 Approach Used: ➡️ Dynamic Programming (DP) — Space Optimized 1. Create two arrays (prev and curr) to store the count of subsequences. 2. Initialize base cases — there’s always one way to form an empty string. 3. For each character in s, compare it with each character in t: If characters match → add ways from both including and excluding it. If not → carry over the previous count. 4. Continue iterating and swap arrays to save space. ✅ Complexity Analysis: Time Complexity: O(n × m) Space Complexity: O(m) → Optimized 1D DP #50DaysChallenge #LeetCode #C++ #DynamicProgramming #Strings #Subsequences #DSA #CodingChallenge #Algorithms
To view or add a comment, sign in
-
-
💻 #2DayOf150 — Remove Duplicates from Sorted Array II (LeetCode #80) Day 2 and still going strong 💪 Today was all about keeping things clean and minimal — both in code and logic. After a solid dry run session, the entire idea just clicked. The two-pointer trick felt like magic once I saw how it limits duplicates perfectly in place ✨ 🧩 Approach Use one pointer to place valid elements Allow only up to 2 occurrences of each number In one pass, the array gets compressed beautifully ✅ Time: O(n) ✅ Space: O(1) ✅ Elegant, minimal, and efficient Dry run tested. Logic locked. Consistency on track 🔥 #DSA #LeetCode #CodingJourney #ProblemSolving #Cplusplus #100DaysOfCode #2DayOf150
To view or add a comment, sign in
-
-
🚀 Day 112 of #LeetCode Challenge! Problem: Diameter of Binary Tree 💡 My Approach: The diameter of a binary tree is the longest path between any two nodes (may or may not pass through the root). The trick is to calculate the height of each subtree while keeping track of the maximum left + right path encountered. Use a helper function height() that: Recursively computes left and right subtree heights. Updates the global diameter as the maximum sum of left and right heights. ✨ Example: Input: [1,2,3,4,5] Output: 3 Explanation: The longest path is [4,2,1,3] or [5,2,1,3] ⏱ Time Complexity: O(N) — visit every node once 💾 Space Complexity: O(H) — recursive stack (H = height of tree) 🌱 Key Insight: At each node, the longest path through it is leftHeight + rightHeight. The overall diameter is the maximum of all such paths. 👨💻 GitHub Link: https://lnkd.in/dvUDMZUC #LeetCode #BinaryTree #Recursion #TreeTraversal #DSA #CodingChallenge #C++ #Day112
To view or add a comment, sign in
-
-
🚀 Day 125 of #LeetCode Challenge! Problem: Binary Tree Preorder Traversal 💡 My Approach: The goal is to perform a preorder traversal of a binary tree — visiting nodes in the order: Root → Left → Right Here’s the step-by-step logic: Start from the root node. Visit (record) the root value first. Recursively traverse the left subtree, then the right subtree. Store values in a vector as you go. ✨ Example Input: [1, null, 2, 3] Output: [1, 2, 3] 🧠 Key Idea Preorder traversal is useful when you need to copy or serialize a tree — it captures the structure starting from the root. ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(H) — recursion stack (H = height of tree) 📎 GitHub Link: https://lnkd.in/gZ6GeXzm #LeetCode #BinaryTree #PreorderTraversal #Recursion #DSA #C++ #ProblemSolving #CodingChallenge #Day125
To view or add a comment, sign in
-
-
🔗 Day 63 of #100DaysOfCode 🔗 🔹 Problem: Valid Parentheses – LeetCode ✨ Approach: Implemented a stack-based validation to ensure every opening bracket has a matching closing one in correct order. Each character is checked systematically — pushing opens and popping closes — making it both clean and efficient! ⚡ 📊 Complexity Analysis: Time Complexity: O(n) — single traversal of the string Space Complexity: O(n) — stack usage for unmatched brackets ✅ Runtime: 2 ms (Beats 97.47%) ✅ Memory: 41.96 MB 🔑 Key Insight: Stacks are the unsung heroes of structured logic — from parentheses validation to syntax parsing, they keep the balance just right. 🧠 #LeetCode #100DaysOfCode #ProblemSolving #DSA #Stack #AlgorithmDesign #CodeJourney #ProgrammingChallenge #LogicBuilding #Efficiency #CodingDaily
To view or add a comment, sign in
-
-
Day 6 – LeetCode Challenge Today, I solved Problem #128: “Longest Consecutive Sequence” using C++. 🔍 Problem Overview: The task is to find the length of the longest consecutive elements sequence in an unsorted integer array. The key challenge is to ensure the solution works in O(n) time complexity. 💡 Approach: To achieve linear time, I used an unordered_set to quickly check if a number exists. For each number, I only begin counting a sequence when it is the start of a new streak (i.e., (num - 1) does not exist in the set). This ensures each number is processed only once. 🧠 Algorithm Design: Insert all elements into an unordered_set for O(1) average lookups. For every number, check if it's the start of a sequence. If yes, count forward (num + 1, num + 2, ... ) while elements exist in the set. Track and update the maximum streak length. ⏱ Time Complexity: O(n) 📌 Space Complexity: O(n) #LeetCode #CPlusPlus #DSA #100DaysOfCode #ProblemSolving #Algorithms #CodingChallenge #TechCommunity #GeetaUniversity
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