99% Efficiency: Mastering Merge Sort on Linked Lists Sorting a Linked List efficiently is a rite of passage for every software engineer. Unlike arrays, we don't have random access, which makes algorithms like Merge Sort the gold standard for achieving O(nlog n) time complexity. Today, I successfully tackled LeetCode #148 (Sort List) with a solution that outperformed 99.18% of Java users. The Technical Breakdown: 1. The "Divide" Phase (Tortoise & Hare): I used the Slow and Fast pointer approach to find the midpoint. By setting fast = head.next, I ensured the slow pointer stopped at the exact spot needed to split the list cleanly into two halves. 2. The "Conquer" Phase (Recursion): By recursively calling sortList, I broke the problem down until I reached the base case of a single node. 3. The "Combine" Phase (Optimized Merge): The magic happens in the merge function. By using a Dummy Node (new ListNode(-1)), I avoided complex if-else checks for the head of the sorted list, allowing for a seamless stitch-up of the two sorted halves. Consistency in the small logic leads to success in the big architecture. Onward! 🔗💻 #DSA #LeetCode #Java #MergeSort #SoftwareEngineering #CodingJourney #ProgrammingLogic #Optimization
Mastering Merge Sort on Linked Lists with 99% Efficiency
More Relevant Posts
-
🚀 Day 48 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Sort Array By Parity Problem Insight: Rearrange the array so that all even numbers come before odd numbers. The order of elements doesn’t matter. Approach: • Used the two-pointer technique (partition logic) • Maintained a pointer j to track the position for even numbers • Traversed the array using i • Whenever an even number is found, swapped it with index j and incremented j • This ensures all even elements move to the front in a single pass Time Complexity: O(n) Space Complexity: O(1) (in-place solution) Key Learnings: • Two-pointer technique is very useful for array partitioning problems • Swapping helps avoid extra space usage • This pattern is similar to problems like moving zeros or segregating positives/negatives Takeaway: Simple logic + optimal approach = clean and efficient solution. Consistency is making these patterns easier to recognize! #DSA #Java #LeetCode #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 13 – Why We Don’t Create Threads Manually in Real Applications Earlier, I used to create threads like this: Thread t = new Thread(() -> { System.out.println("Task running"); }); t.start(); 👉 Works fine… but not ideal for real-world applications. --- 💡 Better approach: ExecutorService ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> { System.out.println("Task executed by thread pool"); }); executor.shutdown(); --- 👉 Why use "ExecutorService"? ✔ Manages a pool of threads (no need to create/destroy repeatedly) ✔ Improves performance and resource utilization ✔ Provides better control (shutdown, scheduling, etc.) --- ⚠️ Insight: Creating too many threads manually can: - Consume more memory - Reduce performance - Make debugging difficult 💡 Real takeaway: In production systems, we focus on managing tasks, not threads directly. #Java #BackendDevelopment #Multithreading #ExecutorService #LearningInPublic
To view or add a comment, sign in
-
Day 42/100 – LeetCode Challenge Problem: Top K Frequent Elements Today I worked on the “Top K Frequent Elements” problem, which focuses on identifying the k most frequent elements from an array. I approached this by first using a HashMap to store the frequency of each element. Once the frequencies were calculated, I converted the map into a list of pairs and sorted it based on frequency. From the sorted structure, I extracted the top k elements by selecting from the highest frequency values. This approach keeps the logic straightforward and easy to follow, especially when prioritizing clarity before optimization. While sorting introduces additional overhead, it provides a clean way to rank elements based on frequency. The solution runs in O(n log n) time due to sorting, with O(n) space complexity. This problem reinforced the importance of frequency counting combined with sorting techniques, and how different approaches can be chosen depending on the trade-off between simplicity and efficiency. Forty-two days in. Consistency is now translating into structured thinking. #100DaysOfLeetCode #Java #DSA #Hashing #Sorting #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 51/100 – LeetCode Challenge Problem: Third Maximum Number Today I solved the “Third Maximum Number” problem, which focuses on identifying the third distinct maximum value in an array. The key challenge here was handling duplicates while keeping track of the top three distinct values. Instead of sorting the array directly, I used a set to eliminate duplicates first. This simplified the problem by ensuring that only unique values were considered. From there, I handled two cases. If there were fewer than three distinct numbers, I returned the maximum. Otherwise, I iterated through the set and tracked the top three maximum values using variables, updating them as I encountered larger numbers. This approach avoids unnecessary sorting and keeps the logic efficient and controlled. The solution runs in O(n) time with O(n) space complexity due to the set. This problem reinforced the importance of handling duplicates carefully and thinking about edge cases before jumping into implementation. Fifty-one days in. The focus is now on writing cleaner logic with fewer assumptions. #100DaysOfLeetCode #Java #DSA #Arrays #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
💻 Day 35 of #LeetCode Journey 🔥 Solved: 19. Remove Nth Node From End of List Today’s problem was all about mastering Linked Lists and understanding the power of the Two Pointer technique. 🔍 Key Idea: Instead of calculating the length, I used a smart approach with fast and slow pointers. Move the fast pointer n steps ahead Then move both pointers together This helps locate the node to remove in a single pass ⚡ Why this approach? Efficient: O(n) time complexity No extra space required Clean and optimal solution 🧠 What I learned: Using a dummy node simplifies edge cases (like removing the head) Two-pointer technique is very powerful in linked list problems 📌 Problem Link: https://lnkd.in/gxXDR-YV #Java #DataStructures #LinkedList #CodingJourney #100DaysOfCode #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
Day 114 - LeetCode Journey Solved LeetCode 572 – Subtree of Another Tree ✅ This problem focuses on determining whether one binary tree is a subtree of another. A subtree must match both in structure and node values, which makes it more than just a simple value comparison problem. Approach: I used a recursive strategy combining two key steps: Traverse each node of the main tree At every node, check if the subtree starting from that node is identical to the given subRoot For checking identical trees, I implemented a helper function that compares: • Node values • Left subtree • Right subtree If all match, we confirm the subtree exists. Otherwise, we continue searching in the left and right branches of the main tree. Complexity Analysis: • Time Complexity: O(n × m) in the worst case, where n is nodes in root and m is nodes in subRoot • Space Complexity: O(h), due to recursion stack Key Takeaways: • Tree problems often require combining traversal + comparison logic • Breaking problems into helper functions simplifies implementation • Understanding recursion flow is crucial for tree-based questions 🌳 All test cases passed successfully 🎯 #LeetCode #DSA #BinaryTree #Recursion #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
💡 Day 55 of LeetCode Problem Solved! 🔧 🌟21. Merge Two Sorted Lists🌟 🔗 Solution Code: https://lnkd.in/gU7m-4wH 🧠 Approach: • Recursive Merge • Checked for null node base cases to identify the ends of the lists. • Recursively compared the current node values of list1 and list2. • Attached the smaller node to point to the recursively merged result of the remaining nodes. ⚡ Key Learning: • Leveraging recursion drastically simplifies Linked List operations, turning complex pointer-splicing logic into an elegant and readable sequence! ⏱️ Complexity: Time: • O(n + m) — where n and m are the lengths of the two lists Space. • O(n + m) — due to the recursion stack #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #LinkedList #Recursion
To view or add a comment, sign in
-
-
🚀 LeetCode Challenge 3/50 💡 Approach: Two Pointer (In-Place) The straightforward way uses an extra array — but the problem specifically says no copying! So I used the Two Pointer technique to solve it in-place with a single pass. 🔍 Key Insight: → Use a 'left' pointer to track where the next non-zero element belongs → Traverse with 'right' pointer — place non-zeros at left, then increment → Fill remaining positions with 0s at the end 📈 Complexity: ✅ Time: O(n) — single pass ✅ Space: O(1) — no extra array, truly in-place Sometimes the constraint IS the optimization. Working within limits pushes us to think smarter! 🧠 #LeetCode #DSA #TwoPointer #Java #ADA #PBL2 #LeetCodeChallenge #Day3of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #MoveZeroes
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟖𝟓 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on moving all zeroes to the end while maintaining order. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Move Zeroes 🔗 https://lnkd.in/dTnpVvBg 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐓𝐰𝐨 𝐏𝐨𝐢𝐧𝐭𝐞𝐫𝐬 • Used a pointer ind to track position for non-zero elements Steps: • Traverse array • If element ≠ 0 → swap with index ind • Increment ind • Ensures all non-zero elements move forward • Zeroes automatically shift to the end 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • In-place operations reduce space complexity • Two-pointer technique is very powerful • Maintaining relative order is important • Simple logic can still be optimal 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Efficiency is not always about complex logic — sometimes it’s about clean and smart implementation. 85 days consistent 🚀 On to Day 86. #DSA #Arrays #TwoPointers #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day 47/100 – LeetCode Challenge Problem: Contiguous Array Today I solved the “Contiguous Array” problem, which involves finding the maximum length of a subarray with an equal number of 0s and 1s. I approached this by transforming the problem into a prefix sum concept. Instead of treating 0 and 1 as they are, I considered 0 as -1 and 1 as +1. This way, whenever the cumulative sum becomes the same at two different indices, it indicates that the subarray between them has an equal number of 0s and 1s. To efficiently track this, I used a HashMap to store the first occurrence of each cumulative sum. As I iterated through the array, I updated the sum and checked if it had been seen before. If yes, I calculated the length of the subarray and updated the maximum length accordingly. This approach avoids brute force and leverages hashing for optimal performance. The solution runs in O(n) time with O(n) space complexity. This problem reinforced how transforming values and using prefix sums can simplify seemingly complex conditions. Forty-seven days in. The thinking process is becoming more structured and intuitive. #100DaysOfLeetCode #Java #DSA #Hashing #PrefixSum #ProblemSolving #Consistency
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