DMITRII’s Substack

Share this post

# 16.05.2023 [24. Swap Nodes in Pairs]

dmitriisamoilenko.substack.com

Discover more from DMITRII’s Substack

I post a problem that I solve every single day
Continue reading
Sign in

# 16.05.2023 [24. Swap Nodes in Pairs]

DMITRII SAMOILENKO
May 16, 2023
Share this post

# 16.05.2023 [24. Swap Nodes in Pairs]

dmitriisamoilenko.substack.com
Share

16.05.2023

24. Swap Nodes in Pairs medium
blog post

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/214

Thanks for reading DMITRII’s Substack! Subscribe for free to receive new posts and support my work.

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
}

Thanks for reading DMITRII’s Substack! Subscribe for free to receive new posts and support my work.

Share this post

# 16.05.2023 [24. Swap Nodes in Pairs]

dmitriisamoilenko.substack.com
Share
Previous
Next
Comments
Top
New

No posts

Ready for more?

© 2023 DMITRII SAMOILENKO
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing