Leetcode problem solving day 88 today i solved problem number 222. Count Complete Tree Nodes link to problem - https://lnkd.in/gWVKj_hb below is my approch Approach 1: Linear Time count nodes recursively one by one. class Solution { public int countNodes(TreeNode root) { return root != null ? 1 + countNodes(root.right) + countNodes(root.left) : 0; } } Time complexity : O(N). Space complexity :O(logN) Approach 2: Binary search Return 0 if the tree is empty. Compute the tree depth d. Return 1 if d == 0. The number of nodes in all levels but the last one is 2 to the power d−1. The number of nodes in the last level could vary from 1 to 2 to the power d. Enumerate potential nodes from 0 to 2 to the power d−1. and perform the binary search by the node index to check how many nodes are in the last level. Use the function exists(idx, d, root) to check if the node with index idx exists. Use binary search to implement exists(idx, d, root) as well. Return 2 to the power d−1 + the number of nodes in the last level. Time complexity :O(log square N) Space complexity : O(1) #DSA #Programming #LeetCode #ProblemSolving #CodingJourney #TechCommunity
Solved LeetCode problem 222: Count Complete Tree Nodes
More Relevant Posts
-
💻 Day 34 of #100DaysOfLeetCode Today’s Challenge: 83. Remove Duplicates from Sorted List 🔹 Problem: Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Key Insight: Because the list is already sorted, duplicates will always be adjacent—this allows us to remove them in a single pass using pointer manipulation. 🔍 Approach: Traverse the list using a pointer. Compare current node with the next node. If values are equal → skip the next node by linking to the next of next. Otherwise → move forward. 🕒 Time Complexity: O(n) 📦 Space Complexity: O(1) ✨ Key Takeaway: This problem reinforces the importance of pointer manipulation and understanding how memory references work in linked lists. A simple check can eliminate duplicates efficiently without using extra space. Link:[https://lnkd.in/gsjVxHXM] #100DaysOfLeetCode #Day34 #LeetCode #ProblemSolving #DSA #Algorithms #LinkedList #CodingChallenge #CodeNewbie #InterviewPreparation #SoftwareEngineering #Programming #CodingCommunity #TechCareers #CareerGrowth #ArjunInfoSolution
To view or add a comment, sign in
-
-
🚀 DSA Progress – Day 99 ✅ Problem #190: Reverse Bits 🧠 Difficulty: Easy | Topics: Bit Manipulation, Binary Representation, Bitwise Operations 🔍 Approach: Implemented a bitwise manipulation method to reverse all 32 bits of an unsigned integer. This problem helps build a strong understanding of how bits can be extracted, shifted, and reassembled — a key concept in low-level programming and embedded systems. Step 1 (Initialization): Start with rev = 0 to store the reversed bits. Step 2 (Extract + Reverse): For each bit position i from 0 to 31: Extract the ith bit using (n >> i) & 1. Move that bit to its reversed position (31 - i) using (bit << (31 - i)). Combine it into rev using bitwise OR (|=). Step 3 (Return Result): After processing all bits, return the reversed number as the final result. 🕒 Time Complexity: O(32) → effectively O(1) (constant time) 💾 Space Complexity: O(1) → no extra data structures used 📁 File: https://lnkd.in/gKeNZQf9 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem deepened my understanding of bit-level operations like shifting (<<, >>) and masking (&, |). It showed how reversing bits is similar to flipping binary mirrors — a useful concept in embedded systems, graphics, and cryptographic algorithms. The challenge reinforced that mastering bitwise logic is essential for writing efficient, low-level optimized code. ✅ Day 99 complete — flipped every bit, reversed the logic, and came out enlightened! ⚡💡💻 #LeetCode #DSA #Python #BitManipulation #Binary #CodingChallenge #InterviewPrep #100DaysOfCode #DailyCoding #GitHubJourney
To view or add a comment, sign in
-
Solved Pow(x, n) (LeetCode #50) recently, and this one turned out to be more than just another coding exercise. 💡 32-bit Integer Insights: 🔹 An integer uses 32 bits: 1 bit is for the sign (positive/negative), and 31 bits store the actual value. 🔹 Negative values: Represented from -1 to -2,147,483,648 (a total of 2,147,483,648 values). 🔹 Positive values: From 1 to 2,147,483,647 (a total of 2,147,483,647 values), since zero also needs a spot. 🔹 That’s why the maximum positive (2,147,483,647) and maximum negative (-2,147,483,648) values in 32-bit integers don’t match. 🔀 My Fix: Convert n to a long before using recursion. This avoids overflow issues and ensures the code works for all edge cases. This challenge not only strengthened my understanding of binary exponentiation, but also revised those crucial details about 32-bit integer representation. #LeetCode #DSA #Programming #100DaysOfCode #BinaryExponentiation #TechLearning #CodingJourney #PGPByAnchal
To view or add a comment, sign in
-
-
Leetcode problem solving day 89 today i solved 124. Binary Tree Maximum Path Sum link to problem - https://lnkd.in/gSXC_ZSA below is my approch Approach 1: DFS function accepts root of the subtree as the input. if the root is null, return 0. This is the base case. If a node does not have a left or right child, then the path sum contributed by the respective subtree is 0. called the function recursively on the left and right child of the root. stored results in gain_from_left and gain_from_right, respectively. If either is negative set it to 0. this is because we don't want to include a path sum contributed by a subtree if it is negative. Updated the maximum path sum (max_sum) seen so far. compared max_sum with the sum of the following and updated it if it is smaller. The value of the root itself. gain_from_left (0 if negative) gain_from_right (0 if negative) Returned the path sum gain contributed by the subtree. This is the maximum of the following two values. The value of the root plus gain_from_left. The value of the root plus gain_from_right. Time complexity: O(n) Space complexity: O(n) #DSA #Programming #LeetCode #ProblemSolving #CodingJourney #TechCommunity
To view or add a comment, sign in
-
-
🚀 Today I practiced one of the most important Linked List problems — Sorting a Linked List efficiently. Instead of converting the list into an array (which increases extra memory usage), I implemented Merge Sort directly on the linked list. 🔍 Why Merge Sort for Linked List? Linked lists don’t have random indexing. Merge Sort works naturally by rearranging pointers. No need of extra space for arrays. 🎯 Result: Time Complexity: O(n log n) Space Complexity: O(log n) due to recursion Stable & Clean Solution 💡 What I learned: Using slow–fast pointer technique to find the middle of the list. Splitting the linked list into two halves efficiently. Merging two sorted linked lists without extra memory. Writing cleaner, structured logic improves readability a LOT. Everyday small progress really compounds. Trying to solve at least one challenge daily 💪 #ConsistencyWins #leetcode #dsa #linkedlist #algorithms #programming #cpp #softwareengineering #codingjourney #learningeveryday #100daysofcode
To view or add a comment, sign in
-
-
📅 October 29, 2025 🧩 Problems Solved: 🔹 House Robber III | Binary Tree, DFS, Dynamic Programming | Medium The key to simplifying this problem is to return two states for every node: 1️⃣ The maximum sum including the current node. 2️⃣ The maximum sum excluding the current node. At each recursive call: For the include case, we add the node’s value plus the sums of left and right subtrees excluding their roots. For the exclude case, we take the maximum of both states from the left and right subtrees, since we can freely choose whether to include or skip them. Finally, the answer is the maximum between the include and exclude sums at the root. ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(n) https://lnkd.in/gSqTztRw 💡 Key Takeaways: • Always think in “states” when dealing with tree DP — defining clear include/exclude relationships often simplifies recursive logic. • Returning multiple values (as a pair or struct) from recursion can greatly reduce redundant recomputation and improve clarity. #LeetCode #100DaysOfCode #DSA #CodingJourney #Cplusplus #ProblemSolving #TechPrep #BinaryTree #DynamicProgramming
To view or add a comment, sign in
-
-
💻 Day 33 of #100DaysOfLeetCode 🔗 Today’s Challenge: Intersection of Two Linked Lists 🔹 Problem: Find the node at which two singly linked lists intersect. If the two linked lists do not intersect, return null. This is a classic problem to test understanding of linked list structure, pointer manipulation, and memory reference. 🔍 Naive Approach: Use nested loops to compare each node in list A with each node in list B. Time Complexity: O(m × n) Not efficient and not recommended for large lists. 🚀 Optimized Two-Pointer Approach: Use two pointers that traverse both lists. When one pointer reaches the end, redirect it to the head of the other list. If they intersect, the pointers will meet at the intersection node. If not, both will reach null simultaneously. 🕒 Time Complexity: O(m + n) 📦 Space Complexity: O(1) Link:[https://lnkd.in/gyTB4GqG] #100DaysOfLeetCode #Day33 #LeetCode #ProblemSolving #Algorithms #DSA #LinkedList #CodingChallenge #CodeNewbie #InterviewPreparation #SoftwareEngineering #Programming #CodingCommunity #TechCareers #CareerGrowth #ArjunInfoSolution
To view or add a comment, sign in
-
-
🧩 Day 64 of #100DaysOfCode 🧩 🔹 Problem: Remove All Adjacent Duplicates in String – LeetCode ✨ Approach: Used a stack-based approach to efficiently remove adjacent duplicates. For each character, if it matches the stack’s top element, pop it — otherwise, push it. A simple yet powerful way to process strings in O(n) time while maintaining clean logic. ⚡ 📊 Complexity Analysis: Time Complexity: O(n) — each character is processed once Space Complexity: O(n) — for the stack and output string ✅ Runtime: 23 ms (Beats 54.52%) ✅ Memory: 45.26 MB (Beats 85.43%) 🔑 Key Insight: Sometimes, solving problems isn’t about brute force — it’s about using the right data structure to make every step count. 💡 #LeetCode #100DaysOfCode #ProblemSolving #DSA #Stack #StringManipulation #CleanCode #CodingChallenge #AlgorithmDesign #LogicBuilding #CodeJourney #Programming
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
-
-
✅Day101/160 #GFG160DAYS DSA CHALLENGE ✅ Today's challenge: Next Greater Elements 🔍 Approach To find the Next Greater Element for each element in an array, I used a stack-based approach while traversing the array from right to left. 1. Initialize an empty stack and a result vector. 2. Traverse the array from the end: While the stack is not empty and the top element is less than or equal to the current element, pop the stack. If the stack becomes empty, the next greater element is -1. Otherwise, the top of the stack is the next greater element. 3. Push the current element into the stack. This approach efficiently determines the next greater element for each array element in a single pass. 💡 Key Learning Points Learned how to effectively use a stack to optimize searching problems. Understood the importance of reverse traversal in problems involving future comparisons. Practiced clean and efficient O(N) time complexity solutions for array-based problems. Reinforced the concept of monotonic stacks, a common pattern in competitive programming. ⏱ Complexity Analysis Time Complexity: O(N) — each element is pushed and popped at most once. Space Complexity: O(N) — for the stack and output array. #DSA #ProblemSolving #Coding #GeeksforGeeks #Stack #C++ #NextGreaterElement #LearningEveryday
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