Binary Search on Ans Optimal approach (using 0 based indexing)
Intuition\nBinary Search on ANS\n# Approach\ntill mid find out whether all element of nums are 0 and checked or not.If yes return ans+1 (as 0 based index is use
# Intuition\nBinary Search on ANS\n# Approach\ntill mid find out whether all element of nums are 0 and checked or not.If yes return ans+1 (as 0 based index is used) if no increase the mid or the range of changeindices vector till which we will try to find whether we can make nums all 0 and checked or not and continue this till all element of nums are 0. at last if in none of the way nums cant be all 0s and checked then return -1(as not possible).\n\n# Complexity\n- Time complexity:\nO(log n*m)\n\n- Space complexity:\nO(m+n)\n\n# Code\n```\nclass Solution {\npublic:\n\n    bool isPossible(vector<int>&nums,vector<int>&changeIndicesZeroBased,int s)\n    {\n        int n=nums.size();\n        vector<int>last(n,-1);\n        for(int i=0;i<=s;i++)\n        {\n            last[changeIndicesZeroBased[i]]=i;\n        }\n\n        int completed=0;\n        int power=0;\n\n        for(int i=0;i<=s;i++)\n        {\n            if(i ==last[ changeIndicesZeroBased[i] ])\n            {\n                if(nums[changeIndicesZeroBased[i]]>power) return false;\n                power = power- nums[changeIndicesZeroBased[i]];\n                completed++;\n            }\n\n            else{\n                power++;\n            }\n        }\n        return completed==n;\n    }\n\n    int earliestSecondToMarkIndices(vector<int>& nums, vector<int>& changeIndices) {\n        int n=nums.size();\n        int m=changeIndices.size();\n        vector<int>changeIndicesZeroBased = changeIndices;\n        for(int i=0;i<m;i++)\n        {\n            changeIndicesZeroBased[i] = changeIndicesZeroBased[i]-1;\n        }\n\n        int low=0;int high=m-1;\n        int ans=-1;\n        while(low<=high)\n        {\n            int mid=(low+high)/2;\n            if(isPossible(nums,changeIndicesZeroBased,mid))\n            {\n                ans=mid;\n                high=mid-1;\n            }\n            else{\n                low=mid+1;\n            }\n        }\n\n        return ans==-1 ? -1 : ans+1;\n    }\n};\n```
['C++']