Day - 93 Binary Tree Right Side View The problem - Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Essentially, return the rightmost node at each level. Brute Force - Perform a complete level-order traversal storing all nodes at each level, then extract only the last node from each level. This gives O(n) time but stores all nodes unnecessarily, wasting O(n) space when we only need one node per level. Approach Used - •) Create result = new ArrayList<>(). •) If root == null, return empty result. •) Create queue = new LinkedList<>(). •) Add root to queue. •) While queue is not empty, 1 - Get current level size, size = queue.size(). 2 - For i = 0 to size - 1, - Poll node from queue, node = que.poll(). - If i == size - 1, add to result: result.add(current.val), this is the last node at current level. - If current.left != null, add to queue: queue.offer(current.left). - If current.right != null, add to queue: queue.offer(current.right). •) Return result. Complexity - Time - O(n), where n is number of nodes. Space - O(w), where w is maximum width of tree. Note - Use level-order BFS to traverse the tree level by level. By tracking the current level size, we can identify the last node processed in each level—this is the rightmost visible node. We only store this last node from each level, efficiently building the right side view in a single traversal. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
Binary Tree Right Side View Traversal
More Relevant Posts
-
Day 32 – Find Target Indices After Sorting Array Solved this problem by identifying the position of target elements after sorting without actually sorting the array. Key Learnings: Using counting technique instead of full sorting Reducing time complexity from O(n²) to O(n) Logical thinking based on sorted order properties #DSA #Java #Arrays #Optimization #CodingPractice #ProblemSolving
To view or add a comment, sign in
-
-
Day 92/100 – LeetCode Challenge ✅ Problem: #49 Group Anagrams Difficulty: Medium Language: Java Approach: Sorting + HashMap Grouping Time Complexity: O(n × k log k) where k = max string length Space Complexity: O(n × k) Key Insight: Anagrams have identical sorted character sequences. Use sorted string as key to group original strings in HashMap. Solution Brief: Iterated through each string in array. Converted to char array and sorted to get canonical form. Used HashMap with sorted string as key, list of original strings as value. If key exists, add to existing list; otherwise create new list. Collected all values from map into result list. #LeetCode #Day92 #100DaysOfCode #HashMap #Sorting #Java #Algorithm #CodingChallenge #ProblemSolving #GroupAnagrams #MediumProblem #String #Anagram #DSA
To view or add a comment, sign in
-
-
Day - 104 Recover Binary Search Tree The problem - You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant O(1) space solution? Brute Force - Perform inorder traversal to collect all values in an array, identify the two swapped elements, store their positions, traverse the tree again to find and swap them back. This gives O(n) time and O(n) space for storing all node values. Approach Used - •) Declare first (first swapped node), second (second swapped node), prev (previous node in inorder traversal). •) Call helper function, helper(root). •) Swap the values, temp = first.val, first.val = second.val, second.val = temp. Helper Function - helper(TreeNode node) •) If node == null, return. •) Traverse left subtree, helper(node.left). •) If prev != null AND prev.val > node.val, - If first == null, set first = prev. - Set, second = node. •) Update, prev = node. •) Traverse right subtree, helper(node.right). Complexity - Time - O(n), where n is number of nodes. Space - O(h), recursion stack depth. Note - In a valid BST, inorder traversal produces a sorted sequence. When two nodes are swapped, it creates violations where prev.val > current.val. For adjacent swaps, there's one violation; for non-adjacent swaps, there are two. By tracking the first and second violating nodes during inorder traversal, we identify the swapped pair. The algorithm handles both cases by always updating second and only setting first once. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 50 / 100 | Median of Two Sorted Arrays Intuition: We are given two sorted arrays and need to find the median of the combined numbers. Since both arrays are already sorted, we can merge them in sorted order. Once we have the merged array, finding the median becomes simple. If the total number of elements is odd, the median is the middle element. If it's even, the median is the average of the two middle elements. Approach: Use two pointers to traverse both arrays. Compare the elements and insert the smaller one into a new array. Continue this process until all elements are merged. Finally, calculate the median based on the length of the merged array. Complexity: Time Complexity: O(n + m) Space Complexity: O(n + m) #100DaysOfCode #Java #DSA #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 49 of #100DaysOfCode Solved 86. Partition List on LeetCode 🔗 🧠 Key Insight: We need to rearrange a linked list such that: 🔹All nodes < x come before nodes ≥ x 🔹While maintaining the original relative order This is a classic linked list partitioning problem. ⚙️ Approach: 1️⃣ Create two dummy lists: 🔹small → nodes with values < x 🔹large → nodes with values ≥ x 2️⃣ Traverse the original list: 🔹Append each node to the appropriate list 3️⃣ Connect both lists: 🔹small → large 4️⃣ Return the head of the new list 🎯 This ensures: 🔹Stable ordering 🔹Clean and efficient separation ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) (no extra nodes, just pointers) #100DaysOfCode #LeetCode #DSA #LinkedList #Algorithms #Java #CodingPractice #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 43 / 100 | Largest Number Intuition: Given a list of non-negative integers and need to arrange them to form the largest possible number. Normal numeric sorting does not work for this problem. Instead, Compare numbers based on their concatenation order. For two numbers a and b, we compare "ab" and "ba". The order that forms the larger concatenated value should come first. Approach: O(n log n) Convert all integers into strings. Sort the array using a custom comparator. For two strings a and b, compare (b + a) with (a + b). If (b + a) is larger, b should come before a. After sorting, concatenate all strings to form the final result. In case the array contains only 0's, the largest element will be "0". Complexity: Time Complexity: O(n log n) Space Complexity: O(n) #100DaysOfCode #Java #DSA #LeetCode #Sorting #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 34 of #100DaysOfCode Solved 852. Peak Index in a Mountain Array on LeetCode ⛰️📈 🧠 Key Insight: A mountain array strictly increases to a peak and then decreases. Instead of scanning the whole array, we can use Binary Search to efficiently find the peak. ⚙️ Approach: 🔹Use binary search with two pointers left and right 🔹Compare arr[mid] with arr[mid + 1] 🔹If arr[mid] > arr[mid + 1] → peak is on the left side (including mid) 🔹Otherwise → peak is on the right side 🔹Continue until left == right, which gives the peak index ⏱️ Time Complexity: O(log n) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #Arrays #Java #ProblemSolving #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🌱 Day 26 of #100DaysOfCode 🚀 📍 Day 26 Progress Started with the core concept of two pointers and how it helps in reducing time complexity for sorted data structures. ✅Worked on problems based on: 📌Prefix Sum 📌Finding pair sum equal to a target in two sorted arrays . Prefix Sum still needs more practice to gain stronger clarity and confidence, especially while handling edge cases. Building pattern recognition step by step 💙 #100DaysOfCode #DSA #TwoPointers #PrefixSum #Java #RevisionMode #LearningInPublic #Consistency
To view or add a comment, sign in
-
🚀 Day 51 of #100DaysOfCode Solved 328. Odd Even Linked List on LeetCode 🔗 🧠 Key Insight: We need to rearrange the linked list such that: 🔹All odd-indexed nodes come first 🔹Followed by all even-indexed nodes 🔹While preserving the relative order ⚠️ Important: This is based on node position (index), not value. ⚙️ Approach: 1️⃣ Create two separate lists: 🔹odd → nodes at odd positions 🔹even → nodes at even positions 2️⃣ Traverse the list and distribute nodes accordingly 3️⃣ Connect: 🔹End of odd list → head of even list 4️⃣ Return the new head 🎯 This ensures a clean separation while maintaining order. ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) (in-place re-linking) #100DaysOfCode #LeetCode #DSA #LinkedList #Algorithms #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 39 of #100DaysOfCode Solved 80. Remove Duplicates from Sorted Array II on LeetCode 🔢 🧠 Key Insight: The array is already sorted, and we need to ensure that each element appears at most twice, modifying the array in-place. ⚙️ Approach: 🔹Maintain a pointer i representing the position to place the next valid element 🔹Start iterating from index 2 🔹For each element nums[j], compare it with nums[i] 🔹If they are different, place the element at nums[i + 2] and move the pointer forward This ensures that no element appears more than twice while maintaining the sorted order. ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #Arrays #TwoPointers #Java #ProblemSolving #InterviewPrep #LearningInPublic
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