🚀 LeetCode Daily Challenge – Day 9 Problem #865: Smallest Subtree with All the Deepest Nodes (Medium) Another solid tree + DFS problem that really tests how well you understand recursion and depth tracking. 🧭 How I Approached the Question: The key was realizing that I don’t just need the depth of each subtree — I also need to know which node represents the smallest subtree containing all deepest nodes. So instead of a normal DFS, I designed a recursive function that returns two things: the height of the subtree the candidate node that could be the answer 🧠 Core Insight: For each node: Recursively compute (height, node) from the left and right subtrees Compare their heights: If left height > right height → deepest nodes are on the left If right height > left height → deepest nodes are on the right If equal → current node becomes the smallest subtree containing all deepest nodes This bottom-up approach ensures that: ✔️ Depth is calculated correctly ✔️ The smallest valid subtree is chosen automatically 🛠️ Why This Works: The deepest nodes define the maximum depth. The lowest common ancestor of all deepest nodes is exactly what the problem asks for. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(h) (recursion stack) This problem was a great reminder that: 👉 Sometimes returning more information from recursion makes the solution much cleaner. 📌 Tree problems get easier once you stop thinking top-down and start thinking bottom-up. #LeetCode #DailyCoding #BinaryTree #DFS #Recursion #ProblemSolving #DSA #Python #CodingJourney
LeetCode Daily Challenge: Smallest Subtree with All Deepest Nodes
More Relevant Posts
-
#week -2 Topic : Arrays - DSA Array : An array is used to store a collection of elements under a single variable ,instead of storing the data indifferent variables which saves the memory. let us discuss some array operations : 1) #max and min num in an array def find_max_min(arr): if not arr: return none max_val=arr[0] min_val=arr[0] for num in arr: if num>max_val: max_val=num if num<min_val: min_val=num return max_val, min_val arr=[1, 6,7,0,4] print(find_max_min(arr) ) 2) #sum of elements arr = [1, 2, 3, 4, 5] total = 0 for num in arr: total += num print(total) def reverse_array(arr): start = 0 end = len(arr) - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 return arr arr = [1, 2, 3, 4, 5] print(reverse_array(arr)) #DSA #python #arrays #learning
To view or add a comment, sign in
-
Day 8 of 365 days of code: Qn 1) Remove the duplicates from the array. Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k. The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored. use two pointer technique. let L=1 starting from position r=1, we overwrite the number at L if nums[r-1]!=nums[r]. this process is like copy pasting the unique elements on the left side of the array, in a sorted order. #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
To view or add a comment, sign in
-
-
🚀 #DAY74 LeetCode Problem #1200 – Minimum Absolute Difference 🧩 Problem Summary Given a list of distinct integers, the goal is to find all element pairs whose absolute difference is the minimum possible and return them in sorted order. 🧠 How It Works First, sort the array to bring close values together Scan once to compute the minimum difference between adjacent elements Scan again to collect all pairs that match this minimum difference This approach leverages the fact that in a sorted array, the smallest difference must occur between neighboring elements. 📘 What I Learned ✔ Why sorting simplifies difference-based problems ✔ How breaking the task into two passes improves clarity ✔ Turning mathematical observations into efficient logic ✔ Writing clean and readable solutions even when performance isn’t maxed 📊 Performance ⏱ Runtime: 95 ms 💾 Memory: 21.57 MB ✅ 38 / 38 testcases passed 📌 Small optimizations, big clarity — consistency is the real win. #LeetCode #DSA #Algorithms #ProblemSolving #Python #CodingPractice #DataStructures #TechJourney #100DaysOfDSA #LearningByDoing #Consistency #InterviewPrep #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 #DAY75 of #100DayofDSA Challenge LeetCode Problem #1200 – Minimum Absolute Difference 🧩 Problem Summary Given a list of distinct integers, the goal is to find all element pairs whose absolute difference is the minimum possible and return them in sorted order. 🧠 How It Works First, sort the array to bring close values together Scan once to compute the minimum difference between adjacent elements Scan again to collect all pairs that match this minimum difference This approach leverages the fact that in a sorted array, the smallest difference must occur between neighboring elements. 📘 What I Learned ✔ Why sorting simplifies difference-based problems ✔ How breaking the task into two passes improves clarity ✔ Turning mathematical observations into efficient logic ✔ Writing clean and readable solutions even when performance isn’t maxed 📊 Performance ⏱ Runtime: 95 ms 💾 Memory: 21.57 MB ✅ 38 / 38 testcases passed 📌 Small optimizations, big clarity — consistency is the real win. #LeetCode #DSA #Algorithms #ProblemSolving #Python #CodingPractice #DataStructures #TechJourney #100DaysOfDSA #LearningByDoing #Consistency #InterviewPrep #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Progress | Problem 9 | Symmetric Tree (Binary Tree) 🌳 Today I solved “Symmetric Tree” and it was a great reminder that trees are all about recursion + structure matching. ✅ Problem: Check if a binary tree is a mirror of itself (symmetric around its center) 🔍 Key Idea: Two trees are mirrors if: their root values are equal left subtree of one == right subtree of the other right subtree of one == left subtree of the other 🧠 Approach Used: 📌 Recursive DFS (Mirror Check) Time: O(n) Space: O(h) (height of tree due to recursion stack) 💡 What I learned: Recursion becomes easy when you define a strong base case Tree problems are mostly about comparing relationships, not just values Mirror logic is a powerful pattern for future problems too 📌 Next target: More binary tree patterns like Level Order, Diameter, Balanced Tree 💪 #LeetCode #DSA #BinaryTree #SymmetricTree #Python #CodingJourney #ProblemSolving #SoftwareEngineering #Consistency
To view or add a comment, sign in
-
-
Mnemosyne v0.2.0 — Release Update I’ve released v0.2.0 of Mnemosyne, an experimental Python library exploring persistent (immutable) data structures with version tracking. Release Note (v0.2.0): https://lnkd.in/gNvd_MQS This version introduces a Persistent Queue built on top of immutable primitives, extending the system beyond stack-only semantics. The internal architecture emphasizes: structural sharing across versions deterministic version history separation between data representation and temporal control. The goal of this release was not feature breadth, but correctness, extensibility, and conceptual clarity—treating data structures as evolving states rather than mutable containers. v0.2.0 establishes a stronger foundation for future work on: -time-aware collections -version diffs and checkpoints -reproducible state transitions -Feedback, discussion, and critical review are welcome. Repo Link: https://lnkd.in/g4TGgUSD #OpenSource #Python #DataStructures #PersistentDataStructures #ComputerScience #ResearchDriven #BuildInPublic
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 10 | 50 𝐃𝐚𝐲𝐬 𝐨𝐟 𝐃𝐚𝐭𝐚 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬 𝐰𝐢𝐭𝐡 𝐏𝐲𝐭𝐡𝐨𝐧 Today’s focus was on the arange() function and Boolean indexing, two simple tools to generate structured arrays and filter data based on clear conditions in NumPy. ✔️ Created NumPy arrays using arange() with custom step sizes ✔️ Filtered values based on conditions (e.g., numbers greater than a threshold) ✔️ Used Boolean indexing to map numerical data back to meaningful labels ✔️ Mapped working-hour conditions back to their corresponding days ✔️ Isolated the peak workload day through vectorized comparison Key insight: Boolean indexing allows you to ask clear questions of your data and get precise answers without loops. Day 10 done. One concept at a time. 🚀 𝐎𝐬𝐭𝐢𝐧𝐚𝐭𝐨 𝐑𝐢𝐠𝐨𝐫𝐞 #Python #NumPy #DataAnalysis #DataScience #MachineLearning #ArtificialIntelligence #DataAnalytics #LearnInPublic #GitHub #Data #TechCommunity #DailyPractice #Consistency #DataDriven #50_days_of_data_analysis_with_python #ostinatorigore
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟭𝟲: The Golden Rule of Feature Scaling ⚠️ Today in #100DaysOfML, I learned how a "simple" preprocessing mistake can ruin your model's credibility: 𝗗𝗮𝘁𝗮 𝗟𝗲𝗮𝗸𝗮𝗴𝗲. If you scale your entire dataset before you split it into training and testing sets, you are "leaking" information from the future into your training process. Your model becomes falsely optimistic because it already "knows" the mean and standard deviation of the test set. 𝗧𝗵𝗲 𝗣𝗿𝗼𝗽𝗲𝗿 𝗪𝗼𝗿𝗸𝗳𝗹𝗼𝘄: 𝟭. 𝗦𝗽𝗹𝗶𝘁 𝗙𝗶𝗿𝘀𝘁: X_train, X_test. 𝟮. 𝗙𝗶𝘁 𝗼𝗻 𝗧𝗿𝗮𝗶𝗻 𝗢𝗡𝗟𝗬: Let the StandardScaler learn from X_train. 𝟯. 𝗧𝗿𝗮𝗻𝘀𝗳𝗼𝗿𝗺 𝗕𝗼𝘁𝗵: Use those learned parameters to scale both sets. 𝗢𝗻𝗲 𝘀𝘂𝗿𝗽𝗿𝗶𝘀𝗶𝗻𝗴 𝗱𝗶𝘀𝗰𝗼𝘃𝗲𝗿𝘆: Standardization does NOT tame outliers. If you have "extreme" data points, scaling them just moves them to a new scale, they stay just as extreme. You have to handle outliers separately! #MachineLearning #DataLeaks #Python #DataPrep #100DaysOfCode #DataEngineering
To view or add a comment, sign in
-
Python with DSA — Day 33 What I worked on: Prime checks: moved from naive divisibility to the √n optimization and the 6k±1 rule to cut unnecessary iterations. Time complexity intuition: compared O(n) vs O(√n) for primality tests; saw how early exits change best/worst cases. Clean loops & edge cases: handled n <= 1, negative inputs, and printed primes from 1–100 with a tight loop. Key snippet (conceptual): Idea: Only test divisors up to √n; if none divide, the number is prime. #Day33 #PythonWithDSA #DataStructures #DSAJourney #ProblemSolving #PythonProgramming #SoftwareEngineer
To view or add a comment, sign in
-
-
Day 75 of #100DaysOfLeetCode Today’s challenge focused on matrix optimization using prefix sums — a great example of turning brute force into an efficient solution. 🟨 Maximum Side Length of a Square with Sum ≤ Threshold (LeetCode 1292) We need to find the largest square submatrix such that: ✔ The sum of all its elements ≤ threshold ✔ Return the maximum possible side length 🧠 My Approach Built a 2D prefix sum array Used it to calculate any submatrix sum in O(1) Checked square sizes efficiently to find the maximum valid one This problem shows how preprocessing can drastically reduce complexity. 💡 What I Learned Prefix sums are extremely powerful for grid problems Brute force becomes practical after optimization Many matrix problems reduce to smart range queries 📊 Complexity Analysis Time Complexity: O(m × n × min(m, n)) Space Complexity: O(m × n) ✅ Day 75 Summary Simple idea. Strong technique. Clean implementation. Progressing steadily toward 100. 🚀 On to Day 76. #100DaysOfLeetCode #Day75 #LeetCode #PrefixSum #Matrix #DynamicProgramming #DSA #ProblemSolving #Python #CodingJourney #AdityaCodes
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