-- Solved LeetCode 100: Same Tree -- Today I worked on the classic binary tree problem “Same Tree”, and it turned out to be a great exercise in strengthening recursion fundamentals -- Problem Summary: -- Given two binary trees, determine whether they are identical in both structure and node values. -- Approach (Recursive DFS): At each node, I focused on 3 key checks: • If both nodes are NULL → trees match at this point • If one is NULL → structure mismatch • If values differ → not the same If all checks pass, recursively compare left and right subtrees. -- Complexity: Time: O(n) – visiting every node once Space: O(h) – recursion stack (depends on tree height) Consistency > Complexity. #LeetCode #DSA #Recursion #BinaryTree #CodingJourney #SoftwareEngineering #algorithm
Same Tree LeetCode Solution with Recursive DFS
More Relevant Posts
-
🚀 LeetCode Daily Challenge 🧩 Problem: Minimum Distance Between Three Equal Elements I You are given an integer array nums. 🎯 Goal Find three indices i < j < k such that: nums[i] == nums[j] == nums[k] And minimize the value: |i - j| + |j - k| + |k - i| If no such triplet exists, return -1. 🧠 Key Intuition First, group all indices of the same value together. For each number: If it appears at least 3 times, we can form a valid triplet. Now the key observation: For minimizing the distance we will take the consecutive triplets. 🛠 Approach 1️⃣ Store indices of each number using a hash map 2️⃣ For each number: If frequency ≥ 3: Iterate through indices in order Consider every consecutive triplet 3️⃣ Compute: distance = |i - j| + |j - k| + |k - i| 4️⃣ Track the minimum distance 5️⃣ If no valid triplet found → return -1 📈 Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) 🔗 Problem https://lnkd.in/dFRkixe5 💻 Solution https://lnkd.in/diUjhYnr #LeetCode #Cpp #DSA #Algorithms #HashMap #Arrays #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge #CompetitiveProgramming #CodingJourney 🚀
To view or add a comment, sign in
-
Day 46 Today I solved: Binary Search (LeetCode 704) 💡 Problem: Given a sorted array, find the index of a target element. If it doesn’t exist, return -1. 💡 My Approach: I used the classic Binary Search technique: 1️⃣ Initialize two pointers: start and end 2️⃣ Find middle index mid 3️⃣ Compare nums[mid] with target 👉 If equal → return mid 👉 If target is greater → search right half 👉 If target is smaller → search left half 4️⃣ Repeat until found or search space is exhausted 💡 Key Insight: Instead of checking every element ❌ Divide the search space in half each time ✅ ⚡ Complexity: Time: O(log n) Space: O(1) #LeetCode #DSA #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Day 21 of my Data Structures & Algorithms Journey 🚀 Solved: Flatten a Multilevel Doubly Linked List (LeetCode 430) 💡 Key Insight: Whenever a node has a child, treat it like a detour — go deep into the child list first, flatten it completely, and then reconnect back to the main list. 🧠 What I learned: • Depth First Search (DFS) approach in linked lists • Handling multiple pointers (next, prev, child) carefully • Importance of saving the next pointer before modifying links • How recursion helps simplify complex structures ⚡ Core Idea: Insert the child list in between the current node and its next node, then reconnect everything smoothly. 🔥 This problem really improved my understanding of pointer manipulation and recursive thinking! #LeetCode #DSA #LinkedList #Recursion #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Solved: Find Peak Element (LeetCode) I recently worked on the “Find Peak Element” problem and implemented an efficient solution using Binary Search. • Runtime: 0 ms (Beats 100%) • Approach: Binary Search • Time Complexity: O(log n) *Approach Summary:- Instead of using a linear scan, I applied binary search to reduce the search space: • If the middle element is smaller than the next element, the peak lies on the right side • Otherwise, the peak lies on the left side • Continue narrowing down until a peak element is found. *Key Takeaways:- • Binary search can be applied beyond sorted arrays • Optimizing from O(n) to O(log n) makes a significant difference • Careful handling of boundary conditions is important Consistently practicing problems like these is helping me strengthen my problem-solving skills and understanding of algorithms. #LeetCode #DSA #BinarySearch #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🧩 Problem: Minimum Absolute Distance Between Mirror Pairs You are given an integer array nums. 🎯 Goal Find the minimum distance between indices i and j such that: One number is the mirror (reverse) of the other i.e., nums[i] == reverse(nums[j]) If no such pair exists, return -1. 🧠 Key Intuition A “mirror pair” means: Reverse the digits of a number Remove leading zeros after reversing Compare with another number Example: 120 → 021 → 21 Efficient idea: While iterating, store the index of reversed numbers For each number: Compute its mirror (reverse) Check if we've already seen its pair This avoids checking all pairs O(n²) 🛠 Approach 1️⃣ Traverse the array 2️⃣ For each number: Convert to string Reverse it Remove leading zeros Convert back to integer → rev 3️⃣ Check in map: If current number exists in map → update answer 4️⃣ Store: map[rev] = current index 5️⃣ Keep track of minimum distance 📈 Complexity Analysis Time Complexity: O(n × d) (d = number of digits) Space Complexity: O(n) 🔗 Problem https://lnkd.in/d_KcNEqb 💻 Solution https://lnkd.in/dvcVRvTu #LeetCode #Cpp #DSA #Algorithms #HashMap #Strings #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge #CompetitiveProgramming #CodingJourney
To view or add a comment, sign in
-
Day 46 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Geometric Sum using Recursion We were given an integer n. Task was to find the sum: 1 + 1/3 + 1/3² + ... + 1/3ⁿ Using recursion. 💻 Approach 🔹️Define a recursive function sum(n). 🔹️Base case: ▪️If n == 0 → return 1 🔹️Recursive case: ▪️Return sum(n-1) + 1/(3ⁿ) Each call adds one term. And moves toward smaller n. 📊 Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) Due to recursion stack. 📚 What I learned today: ▫️Recursion can be used for summation of series. ▫️Each recursive call adds one term to the result. ▫️Understanding base case is important to stop recursion. ▫️Power calculations are common in series problems. Day 46 completed. Getting more comfortable with recursive formulas 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
-- Solved: Sum of Distances (LeetCode 2615) -- Today I worked on a problem that looks simple at first… but quickly punishes brute force thinking. -- Problem Insight For each index, calculate the sum of distances to all other indices with the same value. -- Mistake I Made - I initially tried comparing every element with every other element having the same value. - It worked for small cases but completely breaks for large inputs. -- Key Optimization The breakthrough came when I realized: - Instead of comparing every pair, group indices by value - Use prefix sums to compute distances efficiently - This reduces the complexity to O(n) Always question: “Can I reuse previous computations?” - Every problem like this improves how I think about scaling solutions. - Less brute force, more structure. #DSA #LeetCode #ProblemSolving #CodingJourney #SoftwareEngineering #Optimization #algorithm
To view or add a comment, sign in
-
-
🚀 Day 25/60 of Daily LeetCode Challenge Today I solved Recover a Tree From Preorder Traversal — a really interesting problem combining strings + recursion + trees. 💡 My Approach: At first, the traversal string looked confusing, but I broke it down step by step. I noticed that: The number of dashes (-) represents the depth of the node The actual number after dashes is the node value So I decided to simulate the tree construction using recursion. 🔹 Step 1: Parse Depth and Value I wrote a helper to count dashes → gives me the depth Then extracted the full number (node value) from the string 🔹 Step 2: Recursive Tree Building I used recursion where I pass the expected depth If the current node’s depth doesn’t match, I return NULL Otherwise: Create the node Move index forward Recursively build left child first, then right child 🔹 Step 3: Maintain Index I kept a global/current index so I always know where I am in the string After processing a node, I update index accordingly 🧠 Key Insight: The important idea is: -> Depth (number of dashes) controls where the node should be placed in the tree Also, preorder means: -> Node → Left → Right, so I followed the same order in recursion ⏱️ Complexity: Time: O(n) (each character processed once) Space: O(h) (recursion stack) #Day25 #LeetCode #BinaryTree #Recursion #DSA #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 7 of My LeetCode Journey Today’s problem: Search in Rotated Sorted Array At first glance, it looks like a normal search problem… but the rotation makes it interesting 🤯 💡 Key Insight: Used Binary Search by identifying which half of the array is sorted at each step. This helps decide where to continue the search efficiently. ⚡ Optimized Approach: Check which half is sorted Decide if target lies in that half Narrow down search space ⏱️ Time Complexity: O(log n) ⚡ Performance: 0 ms (Beats 100%) 🧠 What I Learned: Binary Search is all about pattern recognition Even “unsorted-looking” arrays can have structure Thinking logically > brute force #LeetCode #DSA #CodingJourney #BinarySearch #ProblemSolving
To view or add a comment, sign in
-
-
🔥 Day 171 of My LeetCode Journey Problem 112: Path Sum 💡 Problem Insight: Today’s problem was about checking whether a binary tree has a root-to-leaf path whose sum equals a target value. The key detail here is root-to-leaf — not any path. Missing that leads to wrong answers. 🧠 Concept Highlight: The solution is a clean use of DFS (recursion): Subtract the current node’s value from the target Move to left and right subtrees When you reach a leaf, check if the remaining sum is zero This ensures you explore all valid paths without unnecessary work. 💪 Key Takeaway: Tree problems often reduce to accumulating state along a path. Instead of storing paths, update the condition as you traverse. ✨ Daily Reflection: This problem reinforced how recursion naturally fits tree traversal. Once you think in terms of paths and state, the solution becomes straightforward. #Day171 #LeetCode #BinaryTree #DFS #PathSum #ProblemSolving #DSA #CodingJourney #Consistency
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