Simple cpp solution in one pass with explanation. O(N) TC
class Solution {
public:
    //Reverse an array
    void reverse(vector<int> &arr)
    {
        int start = 0, end = arr.size() - 1;
        
        while(start < end)
            swap(arr[start++], arr[end--]);
    }
    
    vector<int> findBuildings(vector<int>& heights) 
    {
        //Start with currMax height as 0
        int currMax = 0;
        vector<int> res;
        
        //Start iterating from end of array
        for(int i = heights.size()-1; i >= 0; i--)
        {
            //If current height of building is greater than any other building in front of it, push to res
            if(heights[i] > currMax)
                res.push_back(i);
            
            //Update currMax height if needed
            currMax = max(currMax, heights[i]);
        }
        //Since we iterated from behind, our indices will be in descending order. reverse and return.
        reverse(res);
        return res;            
    }
};
Comments (0)