Ever wondered what a binary tree looks like from the right side? 🌳👀 Let’s find out! Hey everyone! Day 300 of my 365-day coding journey brought me to a classic tree traversal challenge: LeetCode's "Binary Tree Right Side View." This problem is a great way to understand level-order traversal and how to extract meaningful patterns from it. Let’s dive in. ⚡ 🛠️ The Problem Given the root of a binary tree, imagine standing on the right side of it — your goal is to return the values of the nodes you can see, ordered from top to bottom. In simple terms, at each level of the tree, you only see the rightmost node. 🌲➡️ 🎯 The Approach I solved this using two efficient variations of Breadth-First Search (BFS), both leveraging a queue for level-order traversal. Solution 1: BFS using Queue (with pop) - Used a queue to process nodes level by level. - Captured the queue size before processing each level. - The last node in each level is the one visible from the right side — added it to the result. Solution 2: BFS using Queue (without pop, using indexing) - Instead of popping nodes, I accessed them by their level range indices. - The last node in each level’s range becomes the right-side view node. - Avoids extra pop operations, keeping traversal clean and efficient. 🧠 Key Takeaways 🌿 BFS is the go-to method for problems that involve levels or hierarchies in trees. 🌿 Tracking level boundaries using queue size is a simple yet powerful trick. 🌿 You can also solve this using DFS by recording the last node visited at each depth — multiple ways, same goal! 💡 Challenge for You! Do you prefer BFS or DFS for tree traversal problems? If you’re a BFS fan, do you use the queue size trick or a sentinel marker to detect level changes? Drop your thoughts below! 💬 📺 Watch My Full Walkthrough I explain both BFS techniques step-by-step in my latest video: https://lnkd.in/gx3xz9mi 🔥 Join the Conversation If you're exploring data structures and algorithms like me, let’s connect! Always great to share ideas and learn together. 🚀 #CodingJourney #DSA #LeetCode #BinaryTree #TreeTraversal #BFS #ProblemSolving #Algorithms #DataStructures #JavaScript #LearningEveryDay #DeveloperLife #Programming #CodeNewbies #TechLearning #365DaysOfCode
Subbareddy karri’s Post
More Relevant Posts
-
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
-
-
Ever wondered how to find a duplicate number without touching the array or using extra space? Let’s decode that today! 🔍✨ Hey everyone! Day 296 of my 365-day coding journey, and today I tackled a classic problem: LeetCode's "Find the Duplicate Number." This challenge is an excellent test of algorithmic thinking — balancing performance, space, and creativity. 🌟 🛠️ The Problem You’re given an array of n + 1 integers, each between 1 and n. One number is repeated — your task is to find it. The catch? You can’t modify the array and should use only constant extra space. 🎯 The Approach I explored three different methods, each with its own strengths and trade-offs: Solution 1: Sort + Linear Search Sort the array first, then perform a single linear scan to check adjacent elements. Simple and effective, but sorting costs O(n log n) time. Solution 2: Using a Set (HashSet) Iterate through the array and store elements in a set. If a number already exists, that’s your duplicate! O(n) time but O(n) extra space. Solution 3: Floyd’s Two Pointer (Cycle Detection) The optimal and most elegant approach. Treat the array as a linked list where each value points to the next index. Using slow and fast pointers, detect the cycle and find the duplicate. This achieves O(n) time and O(1) space — brilliant use of logic and pattern recognition! 🧠 Key Takeaways • Every problem has layers — start simple, then optimize. • The time-space trade-off is one of the most important concepts in algorithm design. • Floyd’s cycle detection is a game changer — a true example of thinking beyond the obvious. 💡 Challenge for You Have you used the fast and slow pointer technique outside of linked lists? Where else have you applied it creatively? Drop your insights below! 💬 📺 Watch My Full Walkthrough I’ve broken down all three methods (especially the two-pointer logic) in my latest video: https://lnkd.in/gYGpdZXN 🔥 Join the Conversation If you love exploring algorithms and understanding the “why” behind them, let’s connect and grow together! 🚀 #CodingJourney #DSA #LeetCode #Algorithms #ProblemSolving #DataStructures #Pointers #CycleDetection #LearningEveryDay #Programming #DeveloperLife #TechCommunity #CodeNewbies #SoftwareEngineering #365DaysOfCode
To view or add a comment, sign in
-
-
🚩 Problem: 238. Product of Array Except Self 🔥 Day 46 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. You must solve it without using division and in O(n) time. 🧠 Intuition: Instead of recalculating products repeatedly, we can compute prefix and suffix products: prefix[i] → product of all elements before index i. suffix[i] → product of all elements after index i. Then, answer[i] = prefix[i] * suffix[i] But to optimize space, we can do this in one pass using constant extra space (excluding the output array). ✅ Optimized Approach (Prefix & Suffix Multiplication): Traverse from left to right, building prefix products in the answer array. Traverse from right to left, multiplying suffix products into the existing answer. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) (excluding output array) ✨ Key Takeaway: This problem highlights the power of prefix-suffix techniques — optimizing from O(n²) to O(n) by reusing partial computations. A great demonstration of how small mathematical insights can lead to highly efficient solutions. Link:[https://lnkd.in/g_Wxm9rc] #100DaysOfLeetCode #Day46 #Problem238 #ProductOfArrayExceptSelf #PrefixSum #SuffixProduct #Java #Algorithms #DSA #LeetCode #ProblemSolving #CodingChallenge #InterviewPreparation #CrackingTheCodingInterview #CodingCommunity #DataStructures #SoftwareEngineering #DeveloperJourney #ArjunInfoSolution #CodeNewbie #Programming #LearnToCode #TechCareers #CareerGrowth #ComputerScience #CodeEveryday #ZeroToHero #CodeLife #CodingIsFun #GeeksForGeeks #GameDeveloper #Unity #JavaDeveloper #AI #MachineLearning
To view or add a comment, sign in
-
-
💻 Day 71 of #LeetCode100DaysChallenge Solved LeetCode 50: Pow(x, n) — a classic math-based problem that enhances recursion, divide and conquer, and optimization thinking. 🧩 Problem: Implement a function to calculate xⁿ (x raised to the power n). Handle both positive and negative exponents efficiently without using built-in library functions. 💡 Approach — Fast Exponentiation (Binary Exponentiation): 1️⃣ If n is 0 → return 1 (base case). 2️⃣ If n is negative → compute 1 / pow(x, -n). 3️⃣ For even n, compute pow(x * x, n / 2). 4️⃣ For odd n, multiply once more by x. 5️⃣ This recursive or iterative approach reduces repeated multiplications. ⚙️ Complexity: Time: O(log N) — each step halves the exponent. Space: O(1) (iterative) or O(log N) (recursive). ✨ Key Takeaways: ✅ Strengthened understanding of binary exponentiation and recursion optimization. ✅ Learned how to handle negative powers and edge cases gracefully. ✅ Practiced a pattern used widely in modular arithmetic and scientific computing. #LeetCode #100DaysOfCode #Java #Math #Recursion #BinaryExponentiation #Optimization #ProblemSolving #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
🔥 Day 152 of #1000DaysOfCode — Matrix Magic Continues! ⚡ 🔗 LeetCode Profile: leetcode.com/u/Rhythan 🔗 GitHub Day 152 Code:https://lnkd.in/gQEsVXQT 🧩 Problem: 867. Transpose Matrix Difficulty: Easy Category: Matrix | 2D Arrays 🧠 Concept Overview: The transpose of a matrix is one of the most foundational matrix operations in computer science and mathematics. It involves flipping the matrix over its main diagonal, which effectively means switching rows with columns. For example: Input: 1 2 3 4 5 6 7 8 9 Output: 1 4 7 2 5 8 3 6 9 ⚙️ Approach Summary: Create a new matrix where the number of rows becomes the number of columns, and vice versa. For each element (i, j) in the original matrix, place it in position (j, i) in the transposed one. The operation is simple yet powerful — a great refresher on index manipulation in 2D arrays. 🧮 Time Complexity: O(m × n) 💾 Space Complexity: O(m × n) 💡 Key Insights: Transposing is essential in matrix multiplication, image transformations, and graph adjacency matrices. Reinforces your understanding of row-column relationships. Also a great reminder that clarity in indexing is crucial when dealing with multidimensional structures. 🚀 Reflection: Day 152 showcases the elegance in simplicity — how a small transformation can entirely change the data perspective. Mastering such fundamentals builds strong intuition for complex data structures and algorithms. Each day adds another layer of depth to your problem-solving arsenal. 💪 Keep the streak alive — code, learn, repeat! 🔥 ✅ Progress: Day 152 of #1000DaysOfCode 💯 Mindset: Transform logic like matrices — systematically and beautifully. #1000DaysOfCode #Day152 #LeetCode #Matrix #Transpose #2DArrays #ProblemSolving #CodingChallenge #Java #Algorithms #RhythanCodes #CodeEveryday #LearnByDoing #ProgrammingJourney #DeveloperMindset #ConsistencyWins #CodingStreak #DailyPractice #DataStructures #MathematicsInCS #KeepBuilding #CodeToLearn #SoftwareEngineering #NeverStopCoding #Rhythan1000DaysChallenge
To view or add a comment, sign in
-
-
Another amazing article by Ashish Pratap Singh today! 🌟 He discussed Big-O Notation, one of the often underrated topics that many teachers skip in college. Understanding this concept is crucial for knowing how our code performs and how it is expected to perform. 💻✨ He started with time complexity, covering examples like O(1), O(log n), O(n), O(n log n), O(n²), and even the explosive O(n!) factorial 🚀—which can create trillions of possibilities even at n = 15! He didn’t just list Big-O—he explained it with examples and proper code, making it stand out as very simple and easy to grasp. 📝💡 Next, he explained space complexity, going beyond the usual discussion of variables and data structures. 🧠💾 He highlighted how recursion and dynamic programming also consume memory, which often goes unnoticed. Finally, he taught how to calculate complexities practically, combining loops and ignoring constants in expressions for a true understanding of code performance. 📊🛠️ A must-read for anyone serious about writing efficient code! 🔥 #BigO #TimeComplexity #SpaceComplexity #CodingTips #Programming #EfficientCode #SoftwareEngineering #CodeOptimization #Recursion #DynamicProgramming #TechLearning #AshishPratapSingh #CodePerformance #DeveloperLife #LearnToCode #AlgorithmAnalysis #ComputerScience #CodingCommunity #TechInsights
To view or add a comment, sign in
-
🚩 Problem: 560. Subarray Sum Equals K 🔥 Day 45 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return the total number of continuous subarrays whose sum equals k. 🧠 Intuition: A naive solution checks every subarray (O(n²)), but we can do better using Prefix Sums + HashMap. We keep track of all prefix sums and how many times each sum occurs. For each element: Compute current prefix sum. Check if (prefixSum - k) exists in the map — it means there’s a subarray that adds up to k. Add the frequency of (prefixSum - k) to the count. ✅ Optimized Approach (Prefix Sum + HashMap): Initialize a HashMap with {0 : 1} to handle subarrays starting from index 0. Maintain sum and count. Traverse through array, updating prefix sum and checking (sum - k) in map. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(n) ✨ Key Takeaway: This problem beautifully demonstrates how prefix sums + hash maps transform a brute-force O(n²) approach into an elegant O(n) solution. A must-know technique for interviews and real-world data stream problems. Link:[https://lnkd.in/g-cv3M96] #100DaysOfLeetCode #Day45 #Problem560 #SubarraySumEqualsK #PrefixSum #HashMap #Java #Algorithms #DSA #LeetCode #ProblemSolving #CodingChallenge #CodingCommunity #InterviewPreparation #CrackingTheCodingInterview #DataStructures #SoftwareEngineering #CodeNewbie #DeveloperJourney #ArjunInfoSolution #Programming #LearnToCode #TechCareers #CareerGrowth #ComputerScience #ZeroToHero #CodeLife #CodingIsFun #GeeksForGeeks #CodeEveryday #GameDeveloper #Unity #JavaDeveloper #AI #MachineLearning
To view or add a comment, sign in
-
-
⚙️ 𝗖𝗿𝗮𝗳𝘁𝗶𝗻𝗴 𝗖𝗹𝗮𝗿𝗶𝘁𝘆 𝘄𝗶𝘁𝗵 𝗙𝗹𝗮𝘀𝗸 In software, there’s a quiet power in simplicity. Frameworks come and go — each promising speed, structure, and scale. But at the heart of great engineering lies one timeless question: “𝘿𝙤 𝙄 𝙘𝙤𝙣𝙩𝙧𝙤𝙡 𝙩𝙝𝙚 𝙨𝙮𝙨𝙩𝙚𝙢, 𝙤𝙧 𝙙𝙤𝙚𝙨 𝙩𝙝𝙚 𝙨𝙮𝙨𝙩𝙚𝙢 𝙘𝙤𝙣𝙩𝙧𝙤𝙡 𝙢𝙚?” That question defined my choice. And that choice was Flask. Flask doesn’t try to impress with noise. It gives you space — to architect your logic, to shape your flow, to own your performance. It’s not just a microframework; it’s a philosophy of clarity, precision, and freedom. I’ve built APIs where every route has intent, every response has meaning, and every decision feels deliberate — not dictated. Through Flask, I learned that scalability isn’t born from complexity — it’s born from understanding. Because in the end, true craftsmanship in code is not about frameworks. It’s about the mind behind them. #Flask #Python #APIDesign #Microservices #SoftwareArchitecture #EngineeringPhilosophy #CleanCode #LeadershipInTech
To view or add a comment, sign in
-
-
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
To view or add a comment, sign in
-
-
Problem 24 : LeetCode 🚀 LeetCod Solved — Problem #448: Find All Numbers Disappeared in an Array (Cyclic Sort Approach) 🧩 Today, I explored another elegant application of the Cyclic Sort algorithm — solving the classic “Find All Numbers Disappeared in an Array” problem from LeetCode. 🔍 Problem Overview Given an array of integers where 1 ≤ a[i] ≤ n (with n being the array size), some elements appear twice while others appear once. The task: Find all numbers that do not appear in the array, with ⏱️ O(n) runtime 🧠 O(1) extra space 💡 My Approach — Cyclic Sort in Action I used Cyclic Sort for an in-place, efficient solution: In-Place Placement: Each number x should ideally be placed at index x - 1. During iteration, if arr[i] isn’t in its correct position and its target spot isn’t already occupied, I swap the two elements. Missing Number Detection: After sorting, I perform a linear scan — for every index i where arr[i] != i + 1, the missing number is i + 1. ⚙️ Results ✅ Time Complexity: O(n) — Runtime 7 ms, beating 47.63% of Java submissions ✅ Space Complexity: O(1) — Achieved true in-place solution (no extra data structures) ✅ Memory: 67.09 MB — beating 5.95% of submissions 🧩 Tech Stack: Java | Cyclic Sort | Array Manipulation | In-Place Algorithms | DSA Every such problem reinforces my understanding of data placement logic, index manipulation, and memory efficiency — skills essential for writing optimized backend and system-level code. #LeetCode #Java #ProblemSolving #DataStructures #Algorithms #CyclicSort #InPlaceAlgorithm #BackendDevelopment #SpringBoot #DSA #LearningInPublic #CodingJourney Link : https://lnkd.in/d4Z8zTE4
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