Binary Search
\n# Code\n\nclass Solution:\n    def earliestSecondToMarkIndices(self, nums: List[int], changeIndices: List[int]) -> int:\n        n = len(nums)\n        m = le
\n# Code\n```\nclass Solution:\n    def earliestSecondToMarkIndices(self, nums: List[int], changeIndices: List[int]) -> int:\n        n = len(nums)\n        m = len(changeIndices)\n        @cache\n        def possible(x):\n            lastpos = {}\n            revlastpos = {}\n            for i in range(x-1,-1,-1):\n                if changeIndices[i] not in lastpos:\n                    lastpos[changeIndices[i]] = i\n                    revlastpos[i] = changeIndices[i]\n            if len(lastpos.keys())!=n:return False\n            removed = 0\n            cnt = 0\n            for i,a in enumerate(changeIndices[:x]):\n                if i in revlastpos:\n                    if i - removed - cnt >= nums[revlastpos[i]-1]:\n                        removed += nums[revlastpos[i]-1]\n                        cnt += 1\n                    else:\n                        return False\n            return True\n        if not possible(m):return -1\n        l,r = 1,m\n        if l > r:return -1\n        while l<r:\n            mid = (l+r) // 2\n            if possible(mid):r = mid\n            else: l = mid+1\n\n        return l\n\n                \n\n```
['Binary Search', 'Python3']