Home > other >  HackerRank: Inserting a Node Into a Sorted Doubly Linked List - Kotlin
HackerRank: Inserting a Node Into a Sorted Doubly Linked List - Kotlin

Time:12-09

Just wondering if someone would be able to help me on a kotlin implementation of the Hackerrank question https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem

I came to the following solution which is only passing 3 out of the 8 tests.

I am confused as to what I am doing incorrectly, as when I searched the internet, I found a Java solution which is very similar - https://www.geeksforgeeks.org/insert-value-sorted-way-sorted-doubly-linked-list/

Any help would be appreciated, I'm at a loss with it.

fun sortedInsert(llist: DoublyLinkedListNode?, data: Int): DoublyLinkedListNode? {
    val node = DoublyLinkedListNode(data)
    if (llist == null) return node
    
    if (llist.data >= data) {
        node.next = llist
        node.next!!.prev = node
        return node
    }
    
    var current = llist
    while (current?.next != null && current.next!!.data < data) {
        current = current.next
    }
    
    node.next = current?.next
    if (current?.next != null) current.next!!.prev = node
    
    node.prev = current
    current?.next = node
    
    return llist
}

CodePudding user response:

HackerRank's test harness appears to be broken for Kotlin, missing a println to separate output for each test case. The reason some pass (including sample tests) is that t=1 for these, so the bug isn't triggered.

See the problem's discussion thread for more complaints about the issue. Some of the complaints go back 3 years as of December 2021, suggesting that this is not a high priority for HR to fix, if they're even aware of the issue. Furthermore, the problem appears to affect boilerplate in other linked list problems in Kotlin such as Reverse a Doubly Linked List.

Here's your code translated into Java 15, which passed HackerRank's judge:

public static DoublyLinkedListNode sortedInsert(
    DoublyLinkedListNode llist, int data
) {
    var node = new DoublyLinkedListNode(data);
    if (llist == null) return node;
    
    if (llist.data >= data) {
        node.next = llist;
        node.next.prev = node;
        return node;
    }
    
    var current = llist;
    while (current.next != null && current.next.data < data) {
        current = current.next;
    }
    
    node.next = current.next;
    if (current.next != null) current.next.prev = node;
    
    node.prev = current;
    current.next = node;
    return llist;
}
  • Related