Time Limit Exceeded, cout before returned printed.


  • 0
    A

    Hello, just wondering whis is this code TLE for [1,2] test case.
    I actually printed to std out
    cout << "returned palin";
    and it is indeed called by the program.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
       bool isPalindrome(ListNode* head) {
    		if (head == NULL) return true;
    		if (head->next == NULL) return true;
    
    		ListNode* slow = head;
    		ListNode* fast = head;
    		//find middle
    		while(fast != NULL && fast->next != NULL){
    			fast = fast->next->next;
    			ListNode* temp = slow->next;
    			slow->next->next = slow;
    			slow = temp;
    		}
    		//even
    		ListNode *toLeft = slow;
    		ListNode *toRight = slow;
    		if(fast == NULL){
    			toLeft = toLeft->next;
    			toLeft->next = toRight;
    		} 
    
                    bool palin = true;
    		while(toLeft != NULL && toRight != NULL){
    			if(toLeft->val != toRight->val){
    			    palin = false;
    	    	            break;
    			}
    			//swap back
    			ListNode *temp = toLeft;
    			toLeft = toLeft->next;
    			toLeft->next = temp;
    			toRight = toRight->next;
    		}
    		
    		cout << "returned palin";
    		return palin;
    	}
    };
    

    also tested this on MVSC 2015 and it returns false.

    int main() {
    
    	ListNode *head = new ListNode(1);
    	ListNode *an = new ListNode(2);
    	head->next = an;
    	an->next = nullptr;
    	Solution a;
    	cout << a.isPalindrome(head);
    
    	return 0;
    }
    

Log in to reply
 

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