🚀 Just solved LeetCode #105 – Construct Binary Tree from Preorder and Inorder Traversal 🌳✅ 🧩 Problem: Given two integer arrays, preorder and inorder, where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, the goal is to construct and return the binary tree. 💡 My Approach: I used recursion to rebuild the tree based on the properties of preorder and inorder traversals. 1️⃣ The first element of the preorder array is always the root of the tree. 2️⃣ Find that root in the inorder array — elements to the left form the left subtree, and elements to the right form the right subtree. 3️⃣ Recursively build the left and right subtrees using the corresponding segments of preorder and inorder arrays. 4️⃣ Return the constructed root node once the recursion completes. This approach efficiently utilizes the traversal properties to reconstruct the binary tree from scratch. 🌲 📘 What I Learned: 🌱 Strengthened my understanding of how preorder and inorder traversals relate to each other. 🧠 Gained deeper insight into recursive problem-solving and subarray management. 🔁 Improved my ability to think recursively and break down problems into smaller components. 💻 Appreciated how recursion beautifully models hierarchical data structures like trees. #LeetCode #Java #ProblemSolving #CodingJourney #DataStructures #BinaryTree
Solved LeetCode #105: Construct Binary Tree from Preorder and Inorder
More Relevant Posts
-
📌 LeetCode Day 60 — #106. Construct Binary Tree from Inorder and Postorder Traversal Problem Description: You are given two integer arrays inorder and postorder representing the inorder and postorder traversal of a binary tree. Your task is to reconstruct the original binary tree from these traversals. Approach: Identify Root: In postorder, the last element is always the root. Find Root Index in Inorder: Using a HashMap, find the position of the root in the inorder array to separate left and right subtrees. Recursive Construction: Build the left subtree from the left part of inorder and corresponding postorder range. Build the right subtree similarly from the right parts. Return Root: Recursively combine subtrees to reconstruct the full tree. Complexity Analysis: Time Complexity: O(n) — each node is processed once using the HashMap lookup. Space Complexity: O(n) — recursion stack + map for index lookup. Hashtags: #BinaryTree #Recursion #HashMap #LogicBuilding #LeetCode100Days #Day60 #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 28 of #100DaysOfCode Today’s challenge was all about understanding frequency patterns in arrays — a simple yet powerful concept in hashing 🔍 LeetCode 1207 – Unique Number of Occurrences 🔢 📌 Problem Summary: Given an integer array, determine whether each value appears a unique number of times. In other words, 👉 No two numbers should share the same frequency. 💡 Example: Input: [1,2,2,1,1,3] Output: true Because frequencies are: 1 → 3 times 2 → 2 times 3 → 1 time All unique ✔️ 🧠 My Approach: I solved it using a combination of HashMap + HashSet: 1️⃣ Count the occurrences of each number using a HashMap. 2️⃣ Insert all frequency values into a HashSet. 3️⃣ If the size of the HashSet equals the size of the map → all frequencies are unique ✔️ 4️⃣ Otherwise → duplicates exist ❌ A clean and efficient hashing technique. ⚙️ Complexity: Time: O(n) ⏱️ Space: O(n) 💾 (storing frequencies) 💡 Key Learning: HashMaps aren’t just for storing counts—they can reveal patterns, validations, and uniqueness constraints when combined with sets. This problem reinforced how frequency-based logic solves many real-world scenarios like: ✔ Detecting duplicates ✔ Comparing patterns ✔ Character/string analysis ✔ Data validation 🔥 Result: Code ran successfully with 0 ms Runtime, accepted on the first attempt! Small challenge, clean logic, satisfying finish 💪 On to the next one! 🚀 #100DaysOfCode #LeetCode #HashTable #Java #ProblemSolving #DSA #CodingJourney
To view or add a comment, sign in
-
-
💻 Day 63 of #LeetCode100DaysChallenge Solved LeetCode 290: Word Pattern — a great problem for strengthening hash mapping and bijection logic between characters and words. 🧩 Problem: Given a pattern and a string s, determine if s follows the same pattern. Each letter in the pattern maps to exactly one unique word in s, and each unique word in s maps to exactly one letter in the pattern. No two letters map to the same word, and no two words map to the same letter. 💡 Approach — HashMap + Set: 1️⃣ Split s into words. If pattern length ≠ word count, return false. 2️⃣ Use two data structures: A HashMap<Character, String> to map pattern → word. A HashSet<String> to track if a word is already mapped. 3️⃣ Iterate through both: If the character was seen before, check if it maps to the same word. If it’s new, ensure the word isn’t already mapped to another letter. 4️⃣ Return true if all pairs match consistently. ⚙️ Complexity: Time: O(N) — one pass through all words. Space: O(N) — for the map and set. ✨ Key Takeaways: ✅ Strengthened understanding of bijections and hash-based pattern matching. ✅ Improved clarity on how to manage two-way mapping between characters and strings. ✅ Practiced clean iteration and map validation logic — crucial for real-world parsing and pattern-matching problems. #LeetCode #100DaysOfCode #Java #HashMap #PatternMatching #DSA #ProblemSolving #WomenInTech #CodingChallenge
To view or add a comment, sign in
-
-
🌟 Day 76 of #100DaysOfCodingChallenge 📘 Problem: LeetCode 73 – Set Matrix Zeroes Today, I explored an important array manipulation problem — setting entire rows and columns to zero if any element in a 2D matrix is zero. 🧩 Problem Understanding Given an m x n matrix, if any cell has the value 0, we must make its entire row and column 0. For example: Input: [ [1, 2, 3], [4, 0, 6], [7, 8, 9] ] Output: [ [1, 0, 3], [0, 0, 0], [7, 0, 9] ] 💡 My Approach (Brute Force) To handle this, I used two extra arrays — one to track rows and another to track columns that should become zero. 🪄 Steps followed: 1️⃣ Traverse the matrix and store the indices of rows and columns containing 0. 2️⃣ Loop through the matrix again and make the elements 0 wherever their row or column index is marked. This simple approach helps clearly visualize how matrix updates propagate. 🧠 Concept Learned: How to access and manipulate specific rows and columns in a 2D array. The importance of auxiliary data structures (like boolean arrays) in preserving information during traversal. 🕒 Complexity: Time: O(m × n) Space: O(m + n) 🧵 Next Step: I’ll be optimizing this approach to an O(1) space solution using the matrix itself as a marker — a neat trick in in-place algorithms! #100DaysOfCode #Day75 #LeetCode #Java #CodingChallenge #ProblemSolving #ArrayManipulation #DataStructures #WomenInTech
To view or add a comment, sign in
-
-
👇 📅 Day 84 of #100DaysOfLeetCode Problem: Find Largest Value in Each Tree Row (LeetCode #515) Approach: The problem requires finding the largest value in each level of a binary tree. This can be efficiently solved using Level Order Traversal (BFS). For each level, store all node values and select the maximum one. Add these maximum values to the result list. Steps: Use a queue to perform level-by-level traversal. For each level, collect node values in a list. Compute the maximum value for that level and add it to the output list. Continue until the queue is empty. Complexity: ⏱️ Time: O(n) — every node is visited once. 💾 Space: O(n) — queue and result storage. 🔗 Problem Link: https://lnkd.in/eQz5GBU8 🔗 Solution Link: https://lnkd.in/eAC_3SwK #LeetCode #100DaysOfCode #BinaryTree #LevelOrderTraversal #BFS #DataStructures #Java #Algorithms #ProblemSolving #DailyCoding #CodingChallenge #BuildInPublic #LearnToCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 45/100 — DSA From Scratch (Medium) Problem Solved: Binary Tree Right Side View Task: Given the root of a binary tree, imagine standing on the right side of it — return the list of node values visible from top to bottom. Approach Used: Used DFS (Depth-First Search) with a right-first traversal approach. At each level, the first node we encounter (while going right to left) represents the rightmost visible node. By keeping track of the level during recursion, we can directly capture the visible nodes from the right side. Complexity: Time Complexity: O(n) — visiting each node once. Space Complexity: O(h) — height of the recursion stack. Notes: Learned a new and elegant DFS technique today — just by prioritizing the right subtree, we can capture the right view naturally without using extra data structures. A small but powerful concept that made tree traversal feel intuitive and satisfying to implement. #Day45 #DSAFromScratch #BinaryTree #RightSideView #DFS #LeetCode #Java #ProblemSolving #LearningEveryday #100DaysOfCode
To view or add a comment, sign in
-
-
LeetCode 104 – Maximum Depth of a Binary Tree 🌳 Today I solved one of the classic problems in data structures: “Given the root of a binary tree, return its maximum depth.” 👉 What’s a binary tree? A binary tree is a hierarchical structure where each node has at most two children: left and right. The maximum depth is simply the longest path from the root down to the farthest leaf. 🧩 Why Recursion Works Best Trees are naturally recursive: Each node is itself the root of a smaller subtree. To solve the whole tree, you solve the left subtree and the right subtree, then combine results. This makes recursion elegant and intuitive compared to iterative approaches. ✅ My Solution public int maxDepth(TreeNode root) { if (root == null) return 0; int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return 1 + Math.max(leftDepth, rightDepth); } 📊 Complexity Time: O(n) → we visit every node once. Space: O(h) → recursion stack depends on tree height. Worst case (skewed tree): O(n) Best case (balanced tree): O(log n) 🎯 Key Takeaway Binary trees are a perfect example of why recursion is powerful. Once you “think recursively,” problems like maximum depth become straightforward. This problem reminded me that elegance in code often comes from matching the solution to the structure of the data. #LeetCode #DataStructures #BinaryTree #Recursion #Java #CodingJourney
To view or add a comment, sign in
-
-
🌳 Day 73 of #100DaysOfCode 🌳 💡 Problem: Binary Tree Inorder Traversal – LeetCode ✨ Approach: Implemented a recursive inorder traversal to explore the binary tree in Left → Root → Right order. A perfect balance of recursion and logic — the beauty of tree traversal lies in its simplicity 🌿 📊 Complexity Analysis: Time Complexity: O(n)** — visiting each node exactly once Space Complexity: O(n)** — due to recursion stack and list storage ✅ Runtime: 0 ms (🔥 Beats 100%) ✅ Memory: 43.25 MB 🔑 Key Insight: Recursion simplifies complex tree structures into elegant solutions — one node at a time 🌱 #LeetCode #100DaysOfCode #DataStructures #BinaryTree #Recursion #ProblemSolving #DSA #AlgorithmDesign #CodeEveryday #ProgrammerJourney #Java #CodingChallenge
To view or add a comment, sign in
-
-
🔥 Day 121 of My DSA Challenge – Remove Duplicates from Sorted List 🔷 Problem : 83. Remove Duplicates from Sorted List 🔷 Goal : Given the head of a sorted linked list, remove all duplicate nodes so that each element appears only once, while maintaining the sorted order. 🔷 Key Insight : This problem is a great example of linked list traversal and pointer management. Because the list is already sorted, all duplicates appear consecutively — which makes it easy to detect and skip them in one pass. The challenge is to handle links carefully so that only unique nodes remain connected. 🔷 Approach : 1️⃣ Initialize a dummy node (with a distinct value) to simplify linking. 2️⃣ Use a tail pointer to build a new list containing only unique elements. 3️⃣ Traverse the list using head: If head.val is not equal to the last added node (tail.val), link it. Otherwise, skip the duplicate. 4️⃣ Update tail.next = null at the end to avoid leftover links. 5️⃣ Return dummy.next as the new head. Time Complexity: O(n) Space Complexity: O(1) This problem strengthens concepts of : ✅ Duplicate handling in linked lists ✅ Pointer-based traversal ✅ Clean in-place modification Sometimes, cleaning a data structure is just about connecting only what truly matters. ⚡ Every small pattern makes a big difference in problem-solving clarity. One more concept locked in 💻 #Day121 #DSA #100DaysOfCode #LeetCode #Java #LinkedList #ProblemSolving #Algorithms #DataStructures #CodingChallenge #DeveloperJourney #EngineerMindset #GrowEveryday
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 66 String Manipulation & Primitive Decomposition 🧩 Task: Given a valid parentheses string, decompose it into its primitive components and then remove the outermost parentheses from each component. Example: Input: s = "(()())(())" Primitive Decomposition: "(()())" + "(())" After removing outermost parentheses: "()()" + "()" Output: "()()()" My Approach: I iterated through the string while keeping a counter to track the balance of open parentheses. When an opening parenthesis ( was found, I incremented the counter. If the count was greater than 1, it meant this parenthesis was not an outermost one, so I appended it to the result. When a closing parenthesis ) was found, I only appended it if the counter was greater than 1 before decrementing. This ensures the final closing parenthesis of a primitive part is excluded. This simple counter-based approach effectively identifies and removes the correct parentheses without needing a more complex data structure like a stack. Time Complexity: O(N) Space Complexity: O(N) Sometimes, a simple counter is all you need to elegantly handle nested structures. It can be a clean and efficient alternative to more complex data structures for certain problems. #takeUforward #100DaysOfCode #Java #ProblemSolving #LeetCode #DataStructures #Algorithms #StringManipulation #CodeNewbie
To view or add a comment, sign in
-
More from this author
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