#100DaysOfCode | Day 7 of my LeetCode challenge : Arrays to Linked Lists! Problem - LeetCode #21 (Merge Two Sorted Lists). While this problem can be solved recursively, I chose the Two-Pointer Iterative Approach. Here is why: Production Safety: Recursion is elegant, but on massive datasets, it risks a StackOverflowError. Iteration is much safer for enterprise-level data. The "Dummy Node" Pattern: By initializing a sentinel/dummy node at the start, I eliminated the need to write clunky if-else checks to determine the new head. It keeps the code clean and implicitly handles edge cases like empty lists. The Complexity : ⏱️ Time Complexity: O(N + M) (Where N and M are the lengths of the two lists). 💾 Space Complexity: O(1) (No extra memory used, just re-pointing existing nodes). Getting this to run perfectly in my local IDE tonight was a great feeling. #100DaysOfCode #Java #LeetCode #SoftwareEngineering #SeniorEngineer #BankingTech #DataStructures #Algorithms
Merging Two Sorted Lists in Java with Two-Pointer Iterative Approach
More Relevant Posts
-
🚀 Day 36 of #100DaysOfCode Today I solved LeetCode 155 – Min Stack 💻 🔍 Problem Summary: Design a stack that supports push, pop, top, and retrieving the minimum element — all in constant time O(1). 🧠 Key Learning: This problem teaches how to optimize operations using an auxiliary stack to track the minimum element efficiently. 💡 Approach: Use two stacks: Main stack → stores all elements Min stack → keeps track of minimum values While pushing: Push element to main stack Push to min stack only if it’s smaller or equal While popping: Remove from min stack if it matches top of main stack 📊 Complexity: Time: O(1) for all operations Space: O(n) 🔥 Takeaway: Using extra space smartly can drastically improve performance. This is a great example of designing efficient data structures. #LeetCode #Java #Stack #DataStructures #Algorithms #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Solved LeetCode 2515 – Shortest Distance to Target String in a Circular Array Today I tackled an interesting problem that highlights the importance of handling circular data structures efficiently. 🔍 Problem Insight: Given a circular array of words, a target string, and a starting index, the goal is to find the minimum number of steps required to reach the target by moving either left or right. 💡 Key Learnings: Circular arrays require thinking beyond linear traversal Always consider both directions (forward & backward) Optimizing distance using min(distance, n - distance) is the key trick Simple logic + correct observation = optimal solution ⚙️ Approach Used: Traverse the array to find all occurrences of the target Calculate distance from the starting index Take the minimum considering circular movement 📈 Complexity: Efficient O(n) solution with constant space 🔥 Takeaway: This problem reinforced how small tweaks (like circular behavior) can change the entire approach. A great example of combining logic + observation for clean and optimal solutions. #LeetCode #Algorithms #ProblemSolving #CodingJourney #Java #DataStructures #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 Day 563 of #750DaysOfCode 🚀 📌 Problem Solved: Shortest Distance to Target String in a Circular Array Today I explored a clean and optimized approach to solving a circular array problem 🔄 💡 Key Insight: Instead of checking all indices, we can expand from the start index in both directions simultaneously 👉 At each step i, we check: Forward → (start + i) % n Backward → (start - i + n) % n ⏱️ The moment we find the target, we return i → which is guaranteed to be the minimum distance 🧠 Why this works: We are exploring layer by layer (like BFS on array) First match = shortest path ✅ No need to scan entire array unnecessarily 🔥 What I Learned: Circular problems can often be solved using modulo arithmetic Expanding outward is more efficient than brute force Think in terms of minimum steps, not positions Consistency is the real game changer 💯 On to Day 564 🚀 #LeetCode #Java #Algorithms #DataStructures #CodingJourney #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 27 of my #30DayCodeChallenge: The Efficiency of Binary Exponentiation! The Problem: Pow(x, n). Implementing the power function to calculate x". While it sounds simple, the challenge lies in handling large exponents (up to 231 - 1) and negative powers without hitting time limits or overflow. The Logic: This problem is a classic example of Divide and Conquer optimized through Binary Exponentiation (also known as Exponentiation by Squaring): 1. Bitwise Breakdown: Instead of multiplying x by itself n times (O(n)), we decompose n into powers of 2. For example, x13 is x8. x4. x¹. This brings our complexity down to O(log n). 2. The Iterative Jump: In every iteration of the loop, we square the current base (x = x x). If the current bit of n is 1 (checked via n & 1), we multiply our result by the current base. 3. Handling the Edge Cases: * Negative Exponents: If n is negative, we calculate xI" and then take the reciprocal (1/result). Overflow: We use a long for n during calculation to avoid overflow when converting -2, 147, 483, 648 to a positive value. The Calculation: By halving the power at each step, we transform a task that could take 2 billion operations into one that takes just 31. One step closer to mastery. Onward to Day 28! #Java #Algorithms #DataStructures #BinaryExponentiation #ProblemSolving #150DaysOfCode #SoftwareEngineer
To view or add a comment, sign in
-
-
Day 23 of my #30DayCodeChallenge: The Art of Pruning! The Problem: Permutations II. Generating all unique permutations of a collection that contains duplicates. The challenge isn't just finding the arrangements, but ensuring we don't repeat work or results. The Logic: This problem is a deep dive into Backtracking with a strategic Pruning layer: 1. The Frequency/State Tracking: Since we have duplicate numbers, we can't just rely on the values themselves. I used a vis [] (visited) boolean array to keep track of which specific index in the array is currently being used in our recursion tree. 2. Sorting for Symmetry Breaking: Before starting the recursion, sorting the array is the secret sauce. By grouping identical numbers together, we can easily identify when we are about to make a "dur"-ate choice." 3. Backtracking: Standard push, recurse, and pop. We explore every valid path, then "undo" our choice by setting vis [j] = false to backtrack and try the next possibility. One step closer to mastery. The logic is getting sharper! Onward to Day 24! #Java #Algorithms #DataStructures #Backtracking #LeetCode #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 100 Days of Code Day-25 LeetCode Problem Solved: Reverse Nodes in k-Group I recently worked on a Linked List problem that focuses on reversing nodes in groups of size k while preserving the remaining structure if the group size is less than k. 🔹 Strengthened my understanding of pointer manipulation 🔹 Improved problem decomposition skills 🔹 Practiced recursive thinking for efficient implementation 💡 Key takeaway: Breaking complex problems into smaller, manageable parts significantly simplifies the solution approach. Continuing to build consistency in problem-solving and deepen my understanding of Data Structures & Algorithms. #LeetCode #DataStructures #Algorithms #Java #ProblemSolving #SoftwareDevelopment
To view or add a comment, sign in
-
-
#100DaysOfCode | Day 2 of my LeetCode challenge. Today’s problem: 1365. How Many Numbers Are Smaller Than the Current Number. While the problem seems simple, it’s a perfect example of how choosing the right data structure can drastically change performance. Here is how I broke it down: 1. The Brute Force Approach The most simple and easy way is to use nested loops to compare every number with every other number. Logic: For each element, loop through the entire array and count smaller values. Time Complexity: O(N^2) Space Complexity: O(N) (to store the result) 2. The Sorting + HashMap Approach A more scalable way is to sort the numbers. In a sorted array, a number's index is equal to the count of numbers smaller than it. Logic: Clone the array, sort it, and store the first occurrence of each number in a HashMap. Time Complexity: O(N log N) (due to sorting) Space Complexity: O(N) (to store the map) Use - Works for any range of numbers (including very large or negative ones). 3. The Frequency Array (Counting Sort Logic) Since the problem constraints were small (0 to 100), this is the most optimized solution. Logic: Count the frequency of each number using an array of size 101, then calculate a running prefix sum. Time Complexity: O(N) (Linear time) Space Complexity: O(1) (The frequency array size is constant) #LeetCode #100DaysOfCode #Java #SoftwareEngineering #DataStructures #Algorithms
To view or add a comment, sign in
-
🌲 Day 38/75: Measuring the Diameter of a Binary Tree! Today’s LeetCode challenge was a step up in complexity: finding the Diameter of a Binary Tree. The diameter is the length of the longest path between any two nodes in a tree, which may or may not pass through the root. The Strategy: This problem is tricky because the longest path isn't always just the height of the left side plus the height of the right side at the root. It could be tucked away in one of the subtrees! I used a recursive Depth-First Search (DFS) that performs two tasks at once: Calculates Height: It returns the height of the current subtree to its parent. Updates Diameter: It calculates the path passing through the current node (leftHeight + rightHeight) and updates a global diameter variable if this path is the longest found so far. Performance: ✅ Runtime: 1 ms ✅ Complexity: $O(n)$ Time | $O(h)$ Space It’s a great example of how to extract multiple pieces of information from a single recursive pass. One more day closer to the 40-day mark! 🚀 #LeetCode #75DaysOfCode #Java #BinaryTree #Recursion #Algorithms #DataStructures #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 41 of #LeetCode Journey 📌 Problem: 2515. Shortest Distance to Target String in a Circular Array Today’s problem focused on understanding circular array traversal and how to calculate the minimum distance efficiently. 💡 Key Insight: In a circular array, movement is not limited to one direction. We can move both: ➡️ Forward ⬅️ Backward (wrap-around) So instead of considering only one path, we compare both possibilities to find the shortest route. 🧠 Approach: ✔️ Traverse the array and locate all positions where the target appears ✔️ For each position, compute: Direct distance from start index Circular wrap-around distance ✔️ Take the minimum among all valid distances ✨ Learning: Circular problems become simple when we break them into: 👉 Direct distance 👉 Wrap-around distance This approach helps in many array and graph-based problems as well. ⏱️ Complexity: Time: O(n) Space: O(1) #Day41 #LeetCode #Java #DSA #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 19 of my #30DayCodeChallenge: Mastering Backtracking! The Problem: Combination Sum. Finding all unique combinations of candidates that sum up to a specific target, where each number can be used an unlimited number of times. The Logic: This problem is a perfect example of how Recursion and Backtracking allow us to explore multiple paths while pruning the ones that don't lead to a solution. 1. State-Space Exploration: I used a recursive approach to explore every possible combination. By passing the current index forward, we ensure we don't pick the same set of numbers in a different order, keeping the results unique. 2. The "Unlimited" Choice: Unlike some problems where you move to the next element immediately, here we have the option to stay on the same element to achieve the "unlimited times" constraint-as long as the remaining target allows it. 3. Backtracking & Pru.. If the current sum exceeds the target. we ston exploring that branch (Backtrack). This keeps the algorithm efficient even as the depth of the recursion grows. One more step toward algorithmic mastery. Onward to Day 20! #Java #Algorithms #DataStructures #Backtracking #ProblemSolving #150DaysOfCode #SoftwareEngineering #LeetCode
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