* Computer Science/Algorithm

1265. print-immutable-linked-list-in-reverse

soicem 2021. 4. 18. 22:30

문제: leetcode.com/problems/print-immutable-linked-list-in-reverse/

 

Account Login - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

1. Recursion

class Solution {
public:
    void printLinkedListInReverse(ImmutableListNode* head) {
        if(!head){
            return;
        }
        printLinkedListInReverse(head->getNext());
        head->printValue();
    }
};

 

Time complexity: O(N)

Space complexity: O(N)

 

2. Constant space complexity

class Solution {
public:
    void printLinkedListInReverse(ImmutableListNode* head) {
        ImmutableListNode* tail = NULL;
        
        while(head != tail){
            ImmutableListNode* node = head;
            
            while(node->getNext() != tail){
                node = node->getNext();
            }
            node->printValue();
            tail = node;
        }
    }
};

Time complexity: O(N^2)

Space complexity: O(1)

 

3. Linear time complexity and less than linear space complexity

class Solution {
public:
    void printDummy(ImmutableListNode* start, ImmutableListNode* end){
        vector<ImmutableListNode*> nodes; // space: sqrt(N)
        while(start != end){
            nodes.push_back(start);
            start = start->getNext();
        }
        
        for(int i = nodes.size() - 1; i >= 0; i--){
            nodes[i]->printValue();
        }
    }
    
    void printLinkedListInReverse(ImmutableListNode* head) {
        int total = 0;
        ImmutableListNode* node = head;
        while(node){
            total++;
            node = node->getNext();
        }
        
        int chunk = sqrt(total);
        vector<ImmutableListNode*> nodes; // space: sqrt(N)
        node = head;
        
        int count = 0;
        
        while(node){
            if(count % chunk == 0){
                nodes.push_back(node);
                count = 0;
            }
            node = node->getNext();
            count++;
        }
        nodes.push_back(NULL);
        
        for(int i = nodes.size() - 2; i >= 0; i--){ // time: sqrt(N)
            printDummy(nodes[i], nodes[i + 1]); // space: sqrt(N) * sqrt(N) == N
        }
    }
};

Time complexity: O(N)

Space complexity: O(sqrt(N)) -> sqrt(N)이 아니라 다 합치면 N이 되야할거같은데?

'* Computer Science > Algorithm' 카테고리의 다른 글

1089. Duplicate Zeros  (0) 2021.05.22
616. Add Bold Tag in String  (0) 2021.05.22
Guess Number Higher or Lower 2  (0) 2021.04.17
My Calendar [1:3]  (0) 2021.04.10
1506. Find Root of N-Ary Tree  (0) 2021.03.30