Not sure why TLE?


  • 0
    S

    Used a simple stack solution moving from right to left.. and keeping the stack sorted.
    OJ says TLE and also 16/16 test cases passed.
    Test running on the 16th input also returns well within timeframe..
    Can someone help here?

    class Solution {
    public:
        vector<int> countSmaller(vector<int>& nums) {
            stack<int> sortedStack;
            stack<int> tempBuffer;
            vector<int> v;
            if(nums.size()==0){
                return v;
            }
            v.push_back(0);
            sortedStack.push(nums[nums.size()-1]);
    
            for(int i=nums.size()-2;i>=0;--i){
                int count = 0;
                while(!sortedStack.empty() && sortedStack.top()<nums[i]){
                    int val = sortedStack.top();
                    sortedStack.pop();
                    tempBuffer.push(val);
                    ++count;
                }
                v.push_back(count);
                sortedStack.push(nums[i]);
                while(!tempBuffer.empty()){
                    sortedStack.push(tempBuffer.top());
                    tempBuffer.pop();
                }
            }
            reverse(v.begin(), v.end());
            return v;
        }
    };
    

Log in to reply
 

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