LeetCode Entry

24. Swap Nodes in Pairs

16.05.2023 medium 2023 kotlin

Swap adjacent ListNodes a-b-c-d -> b-a-d-c.

24. Swap Nodes in Pairs medium blog post substack

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/214

Problem TLDR

Swap adjacent ListNodes a-b-c-d -> b-a-d-c.

Intuition

Those kinds of problems are easy, but your task is to write it bug free from the first go.

Approach

For more robust code:

  • use dummy head to track for a new head
  • use explicit variables for each node in the configuration
  • do debug code by writing down it values in the comments

    Complexity

  • Time complexity: \(O(n)\)
  • Space complexity: \(O(1)\)

Code


fun swapPairs(head: ListNode?): ListNode? {
    val dummy = ListNode(0).apply { next = head }
    var curr: ListNode? = dummy
    while (curr?.next != null && curr?.next?.next != null) {
        // curr->one->two->next
        // curr->two->one->next
        var one = curr.next
        var two = one?.next
        val next = two?.next
        curr.next = two
        two?.next = one
        one?.next = next

        curr = one
    }
    return dummy.next
}