Can someone tell me why I am getting TLE error?


  • 0
    S

    Following is my code. I am getting Time Limit Exceeded error, I tried the input [1,4,3,2,6,2] and x = 3.

    if(head == null || head.next == null)
            return head;
        
        ListNode small = head;
        ListNode large = head;
        
        ListNode l = new ListNode(0);
        ListNode lFinal = l;
        
        while(small != null || large != null){
            if(small != null){
                
                if(small.val < x){
                    l.next = small;
                    l = l.next;
                }
                small = small.next;
            }
            if(large != null){
                
                if(large.val < x){
                    
                    large = large.next;
                }
                else if(small == null && large.val >= x){
                    
                    l.next = large;
                    l = l.next;
                    large = large.next;
                } 
            }
        }
        
        return lFinal.next;
    

    I debugged and found

    else if(small == null && large.val >= x){
    
                l.next = large;
                l = l.next;
                large = large.next;
            } 
    

    section is getting 4 3 4 3 4 3 4 3 4 3 4 3 4 3 .......
    Not sure how it's getting value 4 back...
    Thank you in advance.


  • 0

    Because there is a circle in your output list. You can avoid this problem by assigning null to the second half's tail.


Log in to reply
 

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