Binary Search On answer
Complexity\n- Time complexity: O(Nlog(N))\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(N)\n Add your space complexity here, e.g. O(n) \n\
# Complexity\n- Time complexity: $$O(Nlog(N))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n    bool check(vector<int> nums,vector<int> &ids,int n){\n        map<int,int> lastId;\n        vector<int> markId(n+1,0);\n        vector<int> order;\n\n        for(int i = n;i >= 0;i--){\n            if(lastId.find(ids[i]) == lastId.end()){\n                lastId[ids[i]] = i;\n                markId[i] = 1;\n                order.push_back(ids[i]);\n            }\n        }\n\n       \n        reverse(order.begin(),order.end());\n       \n        int count = 0;\n        int orderId = 0;\n\n        for(int i = 0;i <= n;i++){\n            if(markId[i]){\n                if(nums[ids[i]] != 0)\n                    return false;\n\n                nums[ids[i]] = -1;\n                count++;\n\n                continue;\n            }\n            \n            if(orderId < order.size()){\n                if(nums[order[orderId]] == 0){\n                    orderId++;\n                    i--;\n                    continue;\n                }\n\n                nums[order[orderId]]--;\n\n                if(nums[order[orderId]] == 0){\n                    orderId++;\n                }\n            }\n\n        }\n      \n        return count == nums.size();\n\n\n    }\n\npublic:\n    int earliestSecondToMarkIndices(vector<int>& nums, vector<int>& ids) {\n        for(auto &it:ids){\n            it--;\n        }\n\n    \n\n        int l = 0,r = ids.size()-1;\n\n        while(l <= r){\n            int mid = (l+r)>>1;\n\n            if(!check(nums,ids,mid)){\n                l = mid + 1;\n            }else{\n                r = mid - 1;\n            }\n\n        }\n\n        if(l+1 > ids.size())\n            return -1;\n        return l+1;\n    }\n};\n```
['Binary Search', 'Greedy', 'C++']