DEV Community

luparinx
luparinx

Posted on

How I Mastered Merging Sorted Lists with Pointer Tactics

πŸ”₯ The Challenge

Problem: Merge two sorted linked lists into one sorted list.

Input: list1 = [1->2->4], list2 = [1->3->4]  
Output: [1->1->2->3->4->4]
Enter fullscreen mode Exit fullscreen mode

🧠 My Battle Strategy

I deployed the Two-Pointer Technique with a Dummy Node vanguard:

  1. Sentinel Node: Created a dummy head to eliminate edge cases.
  2. Pointer March: Advanced through both lists like shadow soldiers
  3. Optimal Selection: Always chose the smaller value to maintain order
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  const dummy = new ListNode(0); // πŸ›‘οΈ My shield against null cases
  let current = dummy;

  while (list1 && list2) {
    if (list1.val <= list2.val) {
      current.next = list1;
      list1 = list1.next!;
    } else {
      current.next = list2;
      list2 = list2.next!;
    }
    current = current.next;
  }

  current.next = list1 || list2; // ⚑ Finishing move
  return dummy.next;
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Key Insights
Space Efficiency: O(1) space complexity by reusing existing nodes

Time Optimization: O(n+m) time by single-pass merging

Elegant Edge Handling: Dummy node prevents null reference headaches

πŸš€ Level Up Challenge

Can you solve this recursively? Here's a sneak peek:

function mergeRecursive(l1: ListNode | null, l2: ListNode | null): ListNode | null {
  if (!l1) return l2;
  if (!l2) return l1;

  if (l1.val < l2.val) {
    l1.next = mergeRecursive(l1.next, l2);
    return l1;
  } else {
    l2.next = mergeRecursive(l1, l2.next);
    return l2;
  }
}
Enter fullscreen mode Exit fullscreen mode

Daily Progress: β–°β–°β–°β–°β–° 4.44% (4/90)
Tags: algorithms, linkedlists, typescript, dsa, programming

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video β†’

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

πŸ‘‹ Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s dayβ€”drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay