Why am I getting a TLE on this input


  • 0
    A

    I was wondering why I get a TLE on the input ({1, 2}, 1)

    public ListNode rotateRight(ListNode head, int n) {
                if(head==null){
                    return null;
                }
                if(n==0){
                    return head;
                }
                int listSize = getSize(head);
                int toTraverse = n % listSize;
                ListNode firstPart = head;
                ListNode secondPart = null;
                ListNode toRet;
                
                if(toTraverse==0){
                    return head;
                }
                for(int i=0; i<toTraverse; i++){
                    head = head.next;
                }
                secondPart = head;
                toRet = secondPart;
                head.next = null;
                while(secondPart.next!=null){
                    secondPart = secondPart.next;
                }
                secondPart.next = firstPart;
                return toRet;
            }
            
            public int getSize(ListNode head){
                int count=0;
                while(head!=null){
                    head = head.next;
                    count++;
                }
                return count;
            }

  • 0
    D

    You created a circular list:

    secondPart = head;

    toRet = secondPart;

    head.next = null;

    // Here: head == toRet == seconPart, and the next is set to null

    // Therefore: this while loop will not be executed even once since secondPart->next == null

    while(secondPart.next!=null){

    secondPart = secondPart.next;

    }

    secondPart.next = firstPart;

    // Then after this: seconPart now points to firstPart, which means the list starts from firstPart and could go back to firstPart. You formed a circular list


Log in to reply
 

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