My "Ring + Fast&Slow" TLE solution, how can I improve it?


  • 1
    W
    var isPalindrome = function(head) {
        if (!head) return true;
        var tail = head;
        var len = 0;
        while (tail && tail.next) {
            len++;
            tail = tail.next;
        }
        len++;
        tail.next = head; // connect head & tail to create a ring.
        
        var ring = len;// used to detect the ring.
        while (tail.val == head.val) {
            if (tail === head || ring === 0) return true;
            head = head.next; // slow pointer
            ring--;
            for (var i = 0; i < len - 1; i++) {
                tail = tail.next;// fast pointer
            }
        }
        return false;
    };
    

    sadly its TLE, How can I improve it?


  • 0
    V

    There are many people using Fast&Slow be variables name,what does that mean?


  • 0
    W

    I guess they mean using 2 pointers but proceed at different pace.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.