Day 6 of #200DaysOfCode! 🚀 Sticking with the Linked List theme, today I tackled one of the most essential problems in the data structure's repertoire: "Merge Two Sorted Lists" (LeetCode 21). If yesterday was about math on lists, today was about structure. The Challenge: Given two sorted linked lists, merge them into one single sorted list. Think of it like shuffling two decks of cards that are already sorted, or zipping a zipper. The Logic (The Zipper Technique): I used an iterative approach with Two Pointers (i for list1, j for list2) and a "Dummy Node" to build the result. Comparison: I compare the values at the head of both lists (i.val vs j.val). Selection: I pick the smaller value, add it to my new list, and move that specific pointer forward. The Loop: I keep doing this until one of the lists runs dry. The Cleanup: Once one list is empty, I simply append the remaining elements of the other list to the end (since they are already sorted!). The Result: Another 0 ms runtime, beating 100.00% of Python submissions! ⚡ It is a simple algorithm, but it is the exact same logic used in the "Merge" step of Merge Sort, making it a powerful pattern to master. Day 6 down. The streak is alive and well! 🔥 Do you prefer solving this Iteratively (like I did) or Recursively? The recursive solution is elegant but scary for large lists! 👇 #200DaysOfCode #Python #LeetCode #LinkedList #Algorithms #MergeSort #TwoPointers #ProblemSolving #CodingChallenge #DeveloperJourney
Merge Two Sorted Linked Lists in Python
More Relevant Posts
-
🚀 Day 11/30 | LeetCode Problem: Merge Two Sorted Lists (21) Problem: You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted linked list and return its head. 💡 Approach (Recursive) Since both lists are already sorted: If one list is empty → return the other. Compare the current values of both lists. Attach the smaller node to the result. Recursively merge the remaining nodes. This keeps the final list sorted automatically. ⏱ Complexity Time Complexity: O(n + m) Space Complexity: O(n + m) (due to recursion stack) 🧠 Python Code class Solution: def mergeTwoLists(self, list1, list2): if not list1: return list2 if not list2: return list1 if list1.val < list2.val: list1.next = self.mergeTwoLists(list1.next, list2) return list1 else: list2.next = self.mergeTwoLists(list1, list2.next) return list2 📌 Example Input: list1 = [1,2,4] list2 = [1,3,4] Output: [1,1,2,3,4,4] 🎯 Key Takeaway When working with sorted data structures, compare and attach is a powerful pattern. Also, recursion makes linked list problems elegant and clean. ✅ Accepted 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day11 #Python #LinkedList #Recursion #DataStructures #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 7 of #200DaysOfCode! 🚀 One week down! Today, I took a break from complex data structures to parse some ancient history: "Roman to Integer" (LeetCode 13). 🏛️ At first glance, this seems like simple addition. You just sum up the symbols, right? III = 1 + 1 + 1 = 3 XV = 10 + 5 = 15 But the "Subtraction Rule" throws a wrench in the works. If a smaller symbol appears before a larger one (like IV or IX), it subtracts instead of adds. The Logic (The Lookahead Technique): Instead of complicated string parsing or multiple passes, I used a clean linear scan with a simple rule: Map the Values: I used a Python Dictionary (Hash Map) to store the values ('I': 1, 'V': 5, etc.) for instant lookups. Iterate & Compare: I looped through the string and simply peeked at the next character. * If Current < Next: It means we are in a subtraction case (like the I in IV). I subtract the current value from the total. Otherwise: I simply add the current value. Example: For MCMXCIV (1994): C (100) < M (1000) → Subtract 100 X (10) < C (100) → Subtract 10 I (1) < V (5) → Subtract 1 This logic handles every edge case in a single pass O(N). The result was a flawless 0 ms runtime, beating 100.00% of Python submissions! 7 days in, and the streak is strong. 🧱 Have you tried the reverse problem (Integer to Roman)? I hear the logic is quite different! 👇 #200DaysOfCode #Python #LeetCode #Algorithms #HashMap #Logic #ProblemSolving #CodingChallenge #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Day 8/30 | LeetCode Problem: Merge Sorted Array (88) Problem: You are given two sorted arrays nums1 and nums2, and two integers m and n representing the number of initialized elements in each array. Merge nums2 into nums1 as one sorted array. The final result should be stored inside nums1. 💡 Approach Since nums1 already has enough space at the end (filled with 0s), Steps: Copy elements of nums2 into the empty positions of nums1 Sort the entire nums1 array This ensures the final array remains sorted. ⏱ Complexity Time Complexity: O((m+n) log(m+n)) → due to sorting Space Complexity: O(1) → in-place modification 🧠 Python Code class Solution: def merge(self, nums1, m, nums2, n): for i in range(n): nums1[m + i] = nums2[i] nums1.sort() return nums1 📌 Example Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] 🎯 Key Takeaway Sometimes a straightforward solution works perfectly. Optimization (like using two pointers from the end) can further improve time complexity — but clarity first, then optimization. ✅ Accepted | 100% Runtime 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day8 #Python #Arrays #Sorting #DataStructures #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀Day 12 of #75DaysofLeetcode LeetCode #11 – Container With Most Water (Medium) Today I solved the classic Two Pointer problem: Container With Most Water. 🔎 Problem Summary: Given an array height, each element represents a vertical line. The goal is to choose two lines such that together with the x-axis they form a container that holds the maximum amount of water. 💡 Key Insight: Instead of checking all pairs (O(n²)), we can use the Two Pointer Technique: ✔ Start with one pointer at the beginning and one at the end ✔ Calculate the container area using area = min(height[left], height[right]) * (right - left) ✔ Move the pointer pointing to the smaller height ✔ Keep track of the maximum area ⚡ Optimal Complexity: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 💻 Python Implementation: from typing import List class Solution: def maxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 max_water = 0 while left < right: area = min(height[left], height[right]) * (right - left) max_water = max(max_water, area) if height[left] < height[right]: left += 1 else: right -= 1 return max_water 📚 This problem reinforced how two pointers can reduce a brute force problem from O(n²) to O(n). Consistency in solving problems daily is slowly improving my problem-solving skills and algorithmic thinking. 💪 #LeetCode #DSA #Python #TwoPointers #ProblemSolving #CodingPractice #100DaysOfCode
To view or add a comment, sign in
-
-
Weekly challenge 5: Recursion To understand recursion, you must first understand recursion. For Week 5 of my algorithm challenge, I decided to tackle a concept that trips up many beginners: Recursive Functions, using the classic Factorial problem. What is Recursion? Instead of using a standard `for` or `while` loop, a recursive function calls **itself** to solve a smaller piece of the problem. It keeps digging deeper until it hits a "Base Case" (the bottom), and then it passes the answers back up the chain. Think of it like a set of Russian nesting dolls. The Trade-off:** > While recursive code is extremely clean and mathematical, it uses more memory. Every time the function calls itself, it adds a new layer to the computer's **Call Stack**. If you forget your Base Case, your program crashes with a "Stack Overflow"! > > I added a visual trace to my Python script so you can literally see the Call Stack growing and shrinking in the console. Check the full code and console output on GitHub: https://lnkd.in/es5TzCUg #Python #Recursion #Algorithms #CodingChallenge #SoftwareEngineering #DataScience
To view or add a comment, sign in
-
sum() vs NumPy vs math.fsum(): Which One Is Faster? Simulation script is available here: https://lnkd.in/ec9ecZxx I benchmarked four ways to sum 1,000,000 floats stored in a Python list: - sum() - np.sum() - np.add.reduce() - math.fsum() Each function was executed 1000 times (after warm-up), and I compared the mean execution time. Result - math.fsum() - fastest - sum() - slightly slower - np.add.reduce() - slower - np.sum() - slowest Surprising? A bit. Why NumPy Lost Here Because the data is a Python list. When calling np.sum(list), NumPy first converts the list into an array. That conversion overhead dominates the runtime. Meanwhile: > sum() works directly with the list > math.fsum() is a C-optimized implementation with better numerical stability The Takeaway NumPy is extremely fast - when working with NumPy arrays. But if your data is already a list and you just need a single aggregation, plain Python may be faster. Performance always depends on context: - Data structure - Memory layout - Conversion cost Benchmark in your real setup - not in theory. #python #numpy #sum #math #fsum
To view or add a comment, sign in
-
-
𝐖𝐡𝐲 𝐱 𝐢𝐧 𝐬𝐞𝐭 𝐟𝐞𝐞𝐥𝐬 𝐢𝐧𝐬𝐭𝐚𝐧𝐭… 𝐛𝐮𝐭 𝐱 𝐢𝐧 𝐥𝐢𝐬𝐭 𝐝𝐨𝐞𝐬𝐧’𝐭 👇 𝑻𝒘𝒐 𝒍𝒊𝒏𝒆𝒔 𝒕𝒉𝒂𝒕 𝒍𝒐𝒐𝒌 𝒕𝒉𝒆 𝒔𝒂𝒎𝒆: ---> x in my_list ---> x in my_set Both answer a simple question: “Is x present?” But their time complexity is very different. 🧾 𝐋𝐢𝐬𝐭𝐬 → 𝐥𝐢𝐧𝐞𝐚𝐫 𝐬𝐞𝐚𝐫𝐜𝐡 (𝐎(𝐧)) 𝑨 𝒍𝒊𝒔𝒕 𝒊𝒔 𝒍𝒊𝒌𝒆 𝒄𝒉𝒆𝒄𝒌𝒊𝒏𝒈 𝒂 𝑵𝒐𝒕𝒆𝒃𝒐𝒐𝒌: You start at page 1… then page 2… then page 3… Worst case: you check every element. nums = [3, 8, 2, 10, 7] 7 in nums # Python checks one-by-one So membership in a list is 𝑶(𝒏) — time grows with size. ⚡ 𝐒𝐞𝐭𝐬 → 𝐡𝐚𝐬𝐡𝐢𝐧𝐠 (𝐚𝐯𝐞𝐫𝐚𝐠𝐞 𝐎(1)) 𝑨 𝒔𝒆𝒕 𝒊𝒔 𝒎𝒐𝒓𝒆 𝒍𝒊𝒌𝒆 𝒂 𝒍𝒐𝒄𝒌𝒆𝒓 𝒔𝒚𝒔𝒕𝒆𝒎. Instead of scanning all elements, Python: Computes a hash of the value Jumps directly to its bucket nums = {3, 8, 2, 10, 7} 7 in nums # direct lookup No scanning. Just direct access → 𝐚𝐯𝐞𝐫𝐚𝐠𝐞 𝐎(1). 𝐈𝐦𝐩𝐨𝐫𝐭𝐚𝐧𝐭 𝐝𝐞𝐭𝐚𝐢𝐥 Set lookup is O(1) on average, not magic. If many values collide into the same bucket (rare but possible), it can degrade — but Python handles hashing well, so in practice it stays near constant time. 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐚𝐥 𝐭𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Use a list when: -order matters -duplicates matter -small dataset Use a set when: -you need fast membership checks -uniqueness matters -solving frequency / existence problems 𝑾𝒉𝒂𝒕 𝒔𝒎𝒂𝒍𝒍 𝑷𝒚𝒕𝒉𝒐𝒏 𝒅𝒆𝒕𝒂𝒊𝒍 𝒔𝒂𝒗𝒆𝒅 𝒚𝒐𝒖 𝒕𝒉𝒆 𝒎𝒐𝒔𝒕 𝒅𝒆𝒃𝒖𝒈𝒈𝒊𝒏𝒈 𝒕𝒊𝒎𝒆? #Python #DataStructures #Algorithms #DSA #CodingTips #LearningInPublic #YogeshLearns
To view or add a comment, sign in
-
🚀 Day 49 of #100DaysOfCode LeetCode #83 – Remove Duplicates from Sorted List Today I solved a classic Linked List problem: 👉 Given the head of a sorted linked list, delete all duplicates such that each element appears only once. 👉 Return the linked list sorted as well. Since the list is already sorted, duplicates will always appear next to each other — which makes the solution efficient and elegant. 💡 Key Insight: Instead of using extra space (like a set), we can simply: Traverse the linked list Compare the current node with the next node Skip the next node if it’s a duplicate 🧠 Python Implementation: class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def deleteDuplicates(head): current = head while current and current.next: if current.val == current.next.val: current.next = current.next.next else: current = current.next return head ✅ Why This Works: Time Complexity: O(n) Space Complexity: O(1) (no extra memory used) Efficient because the list is already sorted Problems like this strengthen understanding of: ✔️ Linked List traversal ✔️ Pointer manipulation ✔️ Writing clean and optimal code Consistency in solving small problems builds strong fundamentals. 💪 #LeetCode #Python #DataStructures #LinkedList #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Insert Interval (LeetCode 57) - Medium I explored a more optimized way to handle intervals when the input is already sorted. Instead of re-sorting everything, I learned how to process the intervals in a single linear pass. Key Learnings: * Linear Scan: Since the input is sorted, we can divide the problem into three logical parts: Before overlap, During overlap (merge), and After overlap. * In-place Merging: For the overlapping part, we simply update the start to the min and the end to the max of the conflicting intervals. * Efficiency: No sorting means we save time! This approach is much faster for pre-sorted data. Complexity: ⏱️ Time Complexity: O(N) — because we only iterate through the list once. 📂 Space Complexity: O(N) — to store the result list. Consistency is the key #LeetCode #CodingJourney #Blind75 #SDEPrep #DataStructures #Python #ProblemSolving #TechCommunity
To view or add a comment, sign in
-
-
Day 6 was the most hands-on day yet. I stopped looking at Python as a collection of rules and started using it as a high-powered filter for data. Here is how Day 6 changed my perspective on Algorithms and Strings: 🔹 The Accumulator Pattern: I learned how to make a loop remember things. Whether it’s counting occurrences, summing up values, or finding the average, it’s all about maintaining a state while the loop churns through data. 🔹 The Search Party: I built logic to find the largest and smallest values in a set. Realizing that Smallest is tricky—you have to be careful with how you initialize your variables, or your starting "zero" might accidentally become your answer. 🔹 Strings are Collections: I used to think of a word as just "text." Now I see it as a sequence. I’ve learned to Slice strings to grab exactly what I need, Strip away the "noise" (whitespace), and use Parsing to extract specific data from a messy block of text. 🔹 The "In" Operator: Python’s readability shines here. Using if 'search_term' in text: feels like writing English, but it’s actually a powerful logical tool for filtering information instantly. Next up: File Handling. I’m moving from typing data manually into the console to letting Python read and analyze entire documents for me. 📂 #Python #DataAnalysis #CodingJourney #BuildInPublic #SoftwareLogic #Algorithms #StringManipulation
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