Day 72: Partition List 🔗 I'm back to linked lists on Day 72 of #100DaysOfCode by solving "Partition List." The challenge is to rearrange a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x, while preserving the original relative order within each partition. My solution uses a two-list approach with dummy nodes: Creation of Two Lists: I initialize two separate dummy nodes: less_dummy and greater_dummy. Partitioning: I iterate through the original list once. If a node's value is less than x, I append it to the less list; otherwise, I append it to the greater list. This inherently preserves the relative order within each group. Merging: After the single pass, I set the next pointer of the tail of the less list to the head of the greater list (less_tail.next = greater_dummy.next). Crucially, I set the tail of the greater list to None to prevent cycles (greater_tail.next = None). This single-pass method achieves an optimal O(n) time complexity and O(1) extra space complexity (excluding the new nodes being rearranged). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #LinkedList #100DaysOfCode #ProblemSolving
Solved Partition List challenge with two-list approach in #100DaysOfCode
More Relevant Posts
-
Day 57: Binary Tree Zigzag Level Order Traversal 🎢 I'm continuing my journey with an advanced tree traversal problem on Day 57 of #100DaysOfCode: "Binary Tree Zigzag Level Order Traversal." The challenge is to return the nodes of a binary tree level by level, alternating the direction of traversal (left-to-right, then right-to-left, and so on). My solution builds upon the standard Breadth-First Search (BFS) algorithm, using a queue (deque): Level Traversal: I process the tree level by level, finding the level_size in each iteration. Direction Toggle: I use a boolean flag (left_to_right) to track the current direction. Zigzag Logic: Inside the level loop, I use a simple conditional: if left_to_right is true, I append the node value normally. If it's false, I insert the node value at the beginning of the current level's list (current_level.insert(0, node.val)). Optimal Flip: After processing the entire level, I flip the left_to_right flag (left_to_right = not left_to_right) for the next level. This single-pass BFS approach ensures all nodes are visited exactly once, achieving an optimal O(n) time complexity and O(n) space complexity. My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #Trees #BFS #100DaysOfCode #ProblemSolving #Zigzag
To view or add a comment, sign in
-
-
DAY-1:CODING CHALLENGE 1.Longest common Prefix substring from given string as input 2.3SUM problem Started with BRUTE-FORCE → checked every triplet. 😀 Worked 😇 but SLOW for big arrays (O(n³)) → TIME LIMIT EXCEEDED. Faced errors along the way: 'int object not iterable' → I wrote sorted(a,b,c) instead of sorted([a,b,c]). 'unhashable type: list' → Tried adding list to set. Fixed by converting to tuple. LOGICAL BUG → Return inside the loop returned early. Fixed by moving return outside. Finally moved to OPTIMAL TWO-POINTER APPROACH: Sort array first. Use two pointers to find pairs for target -nums[i]. Skip duplicates carefully. Complexity reduced to O(n²). 💡 Lessons learned: small syntax mistakes can cause big errors, immutable types are key for sets, and proper pointer logic makes code efficient. #Python #Algorithms #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 62: Recover Binary Search Tree (BST) 🌳 I'm continuing my journey on Day 62 of #100DaysOfCode with a challenging BST problem: "Recover Binary Search Tree." The task is to fix a BST where exactly two nodes have been swapped by mistake, all without changing the tree's structure. The key insight relies on the property of Inorder Traversal of a BST, which always yields nodes in ascending order. Inorder Traversal: I first perform a standard inorder traversal (using recursion) to store the node values in an ascending list (inorder). Finding Swapped Nodes: I then iterate through the inorder list to find the two misplaced nodes. A violation occurs when inorder[i-1] > inorder[i]. The first misplaced node (first) is the larger element of the first violation. The second misplaced node (second) is the smaller element of the last violation. Correction: Finally, I swap the values of the two nodes found in the original tree. This method achieves an O(n) time complexity and O(n) space complexity (due to storing the inorder array). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #BST #InorderTraversal #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
🧩 Day 29 — 3Sum Closest (LeetCode 16) 📝 Problem Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 🔁 Approach -Sort the array to use the two-pointer technique effectively. -Iterate through each element nums[i] (except the last two) and treat it as the first element of the triplet. -For each i, set two pointers: -left = i + 1 -right = len(nums) - 1 -Compute the sum of the three numbers: -total = nums[i] + nums[left] + nums[right] -If total == target, return total immediately (perfect match). -Otherwise, compare the absolute difference between total and target to update the closestSum. -Adjust pointers: -If total < target, move left pointer right to increase sum. -If total > target, move right pointer left to decrease sum. -Continue until all triplets are checked. -Return the final closestSum. 📊 Complexity -Time Complexity: O(n²) -Space Complexity: O(1) 🔑 Concepts Practiced -Sorting and two-pointer pattern -Optimization using sorted array and pointer movement -Handling duplicates efficiently -Absolute difference comparison for closest value #Leetcode #python #DSA #Sorting #problemSolving
To view or add a comment, sign in
-
-
Problem: Given a string containing ()[]{}, determine if the parentheses are valid. A string is valid if brackets close in the correct order and type. ⬇️ ⬇️ ⬇️ My initial intuition: 😎 Thought of using a stack immediately — push openings, pop on closings. ☠️ But the first few implementations broke on tricky cases like ([)]. 🤡 I was popping and comparing in the wrong order and couldn’t figure out how to validate the pairings cleanly. ⬇️ ⬇️ ⬇️ After careful debugging: 😎 Discovered that flipping my mapping made the logic much simpler: { ')': '(', ']': '[', '}': '{' } 💡 This way, every closing bracket directly tells me which opening it expects. 😎 The stack now works perfectly — last in, first out — catching even the toughest edge cases. 🌟🌟🌟 learned about little micro optimizations: -> to create a local reference of the map helps with access times. -> not unravelling map with .values() calls, instead created a set of opening parenthesis. ✅ Intuition was right this time. 😅 Execution... not so much. #LeetCode #ProblemSolving #Python #LearningJourney #Coding
To view or add a comment, sign in
-
-
🧩 Day 30 — 4Sum (LeetCode 18) 📝 Problem -Given an integer array nums, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: -a, b, c, and d are distinct indices -nums[a] + nums[b] + nums[c] + nums[d] == target -Return the answer in any order. 🔁 Approach -Sort the array to handle duplicates efficiently. -Use a recursive k-sum approach that generalizes 2-sum, 3-sum, and 4-sum problems. -For k > 2, recursively reduce the problem: -Fix one number and call kSum for k - 1 on the remaining array. -Skip duplicates to avoid repeating quadruplets. -For k = 2, use the two-pointer technique: -Move pointers inward based on the sum comparison with the target. -Add valid pairs to the result and skip duplicates. -Backtrack after each recursive call to explore all possible combinations. 📊 Complexity -Time Complexity : O(n³) -Space Complexity : O(k) 🔑 Concepts Practiced -Recursive K-Sum pattern -Two-pointer technique -Sorting and duplicate handling -Backtracking with controlled search space #python #DSA #4Sum #ProblemSolving #Leetcode
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 98 Problem: Count and Say 🔢🗣️ This problem is a fun example of string construction and pattern recognition, where each term of the sequence describes the previous one — a great exercise in iterative logic and encoding patterns. 🧠 Problem Summary: The Count and Say sequence is defined recursively: countAndSay(1) = "1" countAndSay(n) is the run-length encoding of countAndSay(n - 1) For example: 1 11 → one 1 21 → two 1s 1211 → one 2, one 1 111221 → one 1, one 2, two 1s ⚙️ My Approach: 1️⃣ Base cases: return "1" for n=1, "11" for n=2. 2️⃣ Start with "11" and iteratively build the next term by counting consecutive identical digits. 3️⃣ Construct each new term using run-length encoding logic. 4️⃣ Repeat this process until reaching the nth term. 📈 Complexity Analysis: Time: O(n × m) → where m is the average length of intermediate strings. Space: O(m) → for storing the temporary encoded string. ✨ Key Takeaway: This challenge reinforces how string processing and pattern generation can be elegantly solved through careful iteration — a perfect blend of logic and observation. 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #StringManipulation #Python #Algorithms #CodingChallenge #TechCommunity #InterviewPrep #LearningEveryday #CountAndSay
To view or add a comment, sign in
-
-
🚀 𝐃𝐚𝐲 𝟏𝟑 𝐨𝐟 #𝟏𝟔𝟎𝐃𝐚𝐲𝐬𝐎𝐟𝐂𝐨𝐝𝐞 — 𝐏𝐚𝐥𝐢𝐧𝐝𝐫𝐨𝐦𝐞 𝐍𝐮𝐦𝐛𝐞𝐫 | 𝐒𝐭𝐫𝐢𝐧𝐠𝐬 🧩 Today’s focus was on a simple yet classic logic check — determining if a number reads the same forward and backward. While it looks straightforward, it’s a great reminder that elegant solutions often come from clarity, not complexity. Problem: 𝐂𝐡𝐞𝐜𝐤 𝐢𝐟 𝐚𝐧 𝐢𝐧𝐭𝐞𝐠𝐞𝐫 𝐢𝐬 𝐚 𝐩𝐚𝐥𝐢𝐧𝐝𝐫𝐨𝐦𝐞. Approach: Convert the integer to a string and compare it with its reverse. Time Complexity: O(n) Space Complexity: O(n) This small exercise reinforces foundational reasoning that scales up when designing more complex systems — where reversing, mirroring, or symmetry detection shows up in data validation, pattern recognition, and even natural language tasks. 🔗 GitHub: https://lnkd.in/gaim_PJS #Python #LeetCode #CodingChallenge #160DaysOfCode #ProblemSolving #DSA #AIEngineerJourney
To view or add a comment, sign in
-
🚀 Day 40 / 100 — #100DaysOfLeetCode 💡 (1625) Lexicographically Smallest String After Applying Operations (Medium) This was a really fun graph + BFS problem disguised as a string manipulation challenge. The trick is realizing that applying the two operations (add & rotate) repeatedly explores a finite set of states, forming an implicit graph, where each node is a string transformation. 🧩 Problem Overview You are given: A numeric string s Two integers a and b You can repeatedly: Add a (mod 10) to all digits at odd indices. Rotate the string right by b positions. Find the lexicographically smallest string possible after any number of operations. ⚙️ Approach — BFS on States Used Breadth-First Search (BFS) to explore all reachable strings: Start from the initial string s. Use a set vis to track visited states. For each string, generate: One by performing addition on odd indices. One by rotating by b. Continue until all unique transformations are explored. Track the smallest lexicographical string seen. 📈 Complexities Time Complexity: O(10 * n) Each state can appear up to 10 times due to modulo operations, and each state has n length. Space Complexity: O(10 * n) For storing visited transformations. ✅ Key Insights The problem is finite because both operations are modular and cyclic. BFS guarantees we explore all possible reachable strings in an optimal manner. Lexicographical comparison after BFS is straightforward — track the smallest string so far. ✨ Takeaway This problem beautifully demonstrates how: “Even string problems can secretly be graph traversal problems.” It’s a neat mix of modular arithmetic, rotation logic, and state-space search. #LeetCode #100DaysOfCode #BFS #GraphTraversal #StringManipulation #ProblemSolving #Python #Algorithms
To view or add a comment, sign in
-
-
✅ Day 96 Completed – Inorder Traversal Today’s challenge was all about performing Inorder Traversal on a binary tree — a fundamental operation in tree data structures. 🧩 Concept: Inorder traversal visits nodes in the Left → Root → Right order. The task was to implement it without using recursion or an explicit stack, making it an interesting optimization problem. 💡 Approach: The solution uses the Morris Traversal algorithm, which cleverly utilizes threaded binary trees to achieve traversal in O(1) space complexity. It creates temporary links (threads) to predecessor nodes. Once a node’s left subtree is visited, the link is removed, ensuring no extra memory usage. ⚙️ Key Highlights: Space-efficient (no recursion/stack) Time complexity: O(N) All test cases passed ✅ (1111/1111 with 100% accuracy) 🌱 Takeaway: This problem deepened my understanding of space-optimized tree traversal techniques and their practical applications. #100DaysOfCode #Day96 #GeeksforGeeks #Python #DataStructures #BinaryTree #InorderTraversal
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
👏