Why is this code getting a Time Limit Exceeded?


  • 0
    A

    Hello,

    Why is my code here returning a TLE?

    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;
    }

Log in to reply
 

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