🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gwdQDKx4 💡 My thought process: The code calculates the sum of all root-to-leaf paths in a binary tree where each node contains either 0 or 1. Each path from root to leaf represents a binary number. The goal is to convert these binary numbers to decimal and return their total sum. The helper function solve performs a depth-first search. It builds a binary string along the current path by adding the node’s value. When a leaf node is reached, the binary string is saved in a vector. The recursion continues for the left and right children until all root-to-leaf paths are explored. In sumRootToLeaf, after collecting all binary path strings, each string is converted to its decimal equivalent using bit shifting. For each character, its value is multiplied by the corresponding power of 2 and added to a running total. The final result is the sum of all converted values. The time complexity is linear based on the number of nodes, and additional space is needed for recursion and storing path strings. 👉 My Solution: https://lnkd.in/gwAHXfX6 If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
Binary Tree Sum of Root to Leaf Paths in C++
More Relevant Posts
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gJUJE-YA 💡 My thought process: The provided code uses a backtracking approach to generate all possible strings of length n that satisfy the happy string condition: no two adjacent characters can be identical. The algorithm builds these strings in lexicographical order by exploring 'a', 'b', and then 'c'. The main logic is in the solve function, which acts as a recursive explorer. It takes the current string and the number of characters left to add. At each step, it tries appending 'a', 'b', and 'c'. Before adding a character, it checks for safety by ensuring that the character is not the same as the last one in the string. This prevents violating the happy constraint. Once a character is added, the function calls itself with n-1 to fill the next position. After finishing that branch of the search, it removes the character to backtrack and try the next alphabetical option. In the getHappyString function, the process starts by launching three separate recursive chains: one with 'a', one with 'b', and one with 'c'. Since the loops and initial calls follow alphabetical order, the allStrings vector is filled with every valid combination in sorted order. Finally, the code checks if the requested index k exists within the total count of generated strings. If k is within bounds, it returns the string at index k-1; otherwise, it returns an empty string. 👉 My Solution: https://lnkd.in/gKDqj84r If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
Day 41 on LeetCode — Count the Number of Consistent Strings ✅ Today’s problem focused on hash maps and efficient character validation in strings. 🔹 Approach Used in My Solution The idea was to first store all allowed characters in a hash map for quick lookup. After that, I iterated through each word and checked whether every character exists in the allowed set. Key steps in the logic: • Store characters from the allowed string in an unordered_map • Traverse each word in the words array • Check every character of the word against the map • If a character is not allowed, mark the word as invalid • Count only the words where all characters are valid This approach keeps the lookup efficient and the implementation straightforward. ⚡ Complexity: • Time Complexity: O(n × m) (n = number of words, m = average length of each word) • Space Complexity: O(1) (since the character set is limited) 💡 Key Takeaways: • Practiced using hash maps for fast membership checks • Strengthened understanding of string traversal and validation • Reinforced building clean and readable solutions for character-based problems #LeetCode #DSA #Algorithms #DataStructures #HashMap #Strings #ProblemSolving #Coding #Programming #Cpp #STL #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity #SoftwareDeveloper #EngineeringJourney
To view or add a comment, sign in
-
-
Day 61 - LeetCode Journey Solved LeetCode 81: Search in Rotated Sorted Array II (Medium) today — a problem that combines binary search + edge case handling + duplicates. This isn’t just a normal binary search. Here, the array is rotated and may contain duplicates, which makes the decision logic more subtle. 💡 Core Idea: At every step, determine which half is sorted. Then decide whether the target lies in that sorted half. If duplicates block the decision, carefully shrink the search space. ⚡ Key Learning Points: • Applying binary search on a rotated array • Handling duplicate values that break clear ordering • Smart boundary adjustments (low++, high--) • Maintaining efficiency close to O(log n) in most cases The real challenge was not writing the code — It was thinking clearly about all possible scenarios. Problems like this strengthen pattern recognition and deepen understanding of search-based algorithms 💯 ✅ Stronger grip on modified binary search ✅ Better handling of tricky edge cases ✅ Improved logical decision-making Each variation of binary search builds sharper intuition. Still learning. Still improving. Still coding 🚀 #LeetCode #DSA #Java #BinarySearch #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 24/60 — LeetCode Discipline Problem Solved: Symmetric Tree (Revision) Difficulty: Easy Today’s practice focused on revisiting a classic binary tree problem — checking whether a tree is symmetric around its center. The key idea is to treat the left and right subtrees as mirror images and recursively compare their corresponding nodes. By verifying both structure and node values simultaneously, the algorithm determines whether the tree maintains perfect symmetry. Problems like this highlight how recursion naturally fits tree-based structures and helps simplify complex comparisons. 💡 Focus Areas: • Strengthened recursive tree traversal • Practiced mirror comparison of subtrees • Improved understanding of binary tree symmetry • Reinforced recursive problem-solving patterns • Focused on writing clean and structured logic ⚡ Performance Highlight: Achieved 0 ms runtime (100% performance) on submission. Consistent practice across arrays, strings, stacks, bit manipulation, and now tree structures continues to deepen my overall algorithmic intuition. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #BinaryTree #Recursion #Algorithms #DataStructures #ProblemSolving #CodingJourney #SoftwareEngineering #Programming #Developers #TechCareers #Java
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/grtpbGeG 💡 My thought process: A counter tracks the number of operations. The loop runs until the string length becomes 1, which means the number has been reduced to 1. If the last character of the string is 0, the number is even in binary. Dividing by 2 is the same as removing the last bit, so pop_back removes the trailing 0. If the last character is 1, the number is odd and needs to be increased by 1. To simulate binary addition, the code goes through the string from right to left. All consecutive trailing 1 characters are changed to 0 to manage the carry. When a 0 is found, it becomes 1, and the carry stops. If the loop finishes without finding a 0, it means the string was made entirely of 1 characters. Adding 1 then results in an extra leading 1, which is added by putting 1 at the front of the string. Each iteration counts as one step. This process continues until only one character is left. The function finally returns the total number of steps needed to reduce the binary number to 1. 👉 My Solution: https://lnkd.in/guc6fia6 If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Journey – Post #2 https://lnkd.in/gMaJrTkJ Today I solved LeetCode Problem #69 – Sqrt(x) using Binary Search. 🔹 Problem Statement: Given a non-negative integer x, return the square root of x rounded down to the nearest integer. 🔹 Approach: Instead of using built-in functions, I implemented Binary Search to find the square root efficiently. • Start the search range from 0 to x • Calculate mid and check mid * mid • If it equals x, return mid • If mid * mid < x, move to the right half • If mid * mid > x, move to the left half • Store the closest possible answer during the search ⏱ Time Complexity: O(log n) 💡 Key Learning: Binary Search can be applied not only on sorted arrays but also on mathematical problems like square roots. I’m continuing my DSA + LeetCode practice and sharing my progress here. #leetcode #dsa #binarysearch #cpp #codingpractice #learninginpublic
To view or add a comment, sign in
-
-
Day 54 - LeetCode Journey Solved LeetCode 744: Find Smallest Letter Greater Than Target (Easy) today using a simple linear search approach. This journey isn’t about solving the hardest problems daily, but about showing up consistently and improving step by step. Even simple problems help in strengthening fundamentals and building confidence. Today’s problem reinforced key concepts like: • Understanding sorted arrays and traversal • Applying linear search efficiently • Handling edge cases (wrap-around condition) • Writing clean and readable logic The idea is straightforward — iterate through the array and return the first character greater than the target, otherwise return the first element 💡 Every problem, easy or medium, adds value to problem-solving skills, and that’s where real growth happens 💯 ✅ Stronger understanding of basic concepts ✅ Improved thinking for edge cases ✅ More confidence in DSA fundamentals Still a long way to go, but progress is progress 🚀 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #Algorithms #Programming #DeveloperJourney #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 23/60 — LeetCode Discipline Problem Solved: Remove Duplicates from Sorted Array (Revision) Difficulty: Easy Today’s practice focused on revisiting a classic array problem that leverages the two-pointer technique. Since the array is already sorted, duplicates naturally appear next to each other. The idea is to maintain one pointer for the position of the last unique element and another pointer to traverse the array, updating the array in-place whenever a new unique value appears. Problems like this beautifully demonstrate how understanding the structure of the data can simplify the solution significantly. 💡 Focus Areas: • Strengthened two-pointer array technique • Practiced in-place array modification • Reinforced understanding of sorted array properties • Improved clean and efficient iteration logic • Focused on writing simple and readable code ⚡ Performance Highlight: Achieved ~79% runtime efficiency on submission. Consistent practice with classic problems continues to refine core algorithmic patterns and strengthen problem-solving discipline. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #TwoPointers #Arrays #Algorithms #DataStructures #ProblemSolving #CodingJourney #SoftwareEngineering #Programming #Developers #TechCareers #Java
To view or add a comment, sign in
-
-
🚀 Day 76 / 100 Days of LeetCode Challenge 🧠 Today’s problem: Minimum Operations to Transform a Binary String I worked on a problem that required counting the number of 0s in a binary string and determining the minimum operations needed based on a given integer k. 📌 Problem intuition: Count the number of zeros in the string. If there are no zeros → already valid → return 0. If the string length equals k and all characters are zeros → 1 operation needed, otherwise -1. Otherwise, compute hase = len - k and proceed with further logic (though the implementation is still in progress). 🔍 Key takeaway: Sometimes the simplest approach—like counting zeros—can form the foundation of a solution. But edge cases like len == k and zero-count logic must be handled carefully to avoid incorrect results. 💻 Code snippet highlights: Loop through string, using bitwise operation ~s.charAt(i) & 1 to count zeros efficiently. Early returns for edge cases. Still refining the full logic, but proud of the progress! 📈 Runtime: 4 ms (Beats 99.66%) 💾 Memory: 47.68 MB (Beats 87.62%) ✅ 999/999 test cases passed #100DaysOfCode #LeetCode #CodingChallenge #Java #ProblemSolving #Algorithms #DataStructures #DeveloperJourney #TechCommunity #DailyCoding #CodeNewbie #WomenInTech #Programming #DevLife #LearnToCode #CodingLife #SoftwareEngineering #Tech #GrowthMindset
To view or add a comment, sign in
-
-
🔥 Day 10 of my coding consistency journey. Today I solved LeetCode Problem 1018 – Binary Prefix Divisible By 5. The task is to check whether the binary number formed at each prefix is divisible by 5. 💡 My Approach: • Instead of forming large binary numbers, I kept track of the current value modulo 5. • For each bit, I updated the value using: num = (num * 2 + current_bit) % 5 • If the result becomes 0, it means the current prefix is divisible by 5. • I stored the result for each prefix in a boolean array. This approach avoids overflow and keeps the solution efficient. Problems like this highlight the importance of modular arithmetic in optimization. Consistency is slowly turning into strength 🚀 #LeetCode #DSA #Algorithms #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
Explore related topics
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