JAVA SOLUTION
\nclass Solution {\n    public int earliestSecondToMarkIndices(int[] nums, int[] ch) {\n        int ans = -1;\n        \n        int n = ch.length;\n        \n 
```\nclass Solution {\n    public int earliestSecondToMarkIndices(int[] nums, int[] ch) {\n        int ans = -1;\n        \n        int n = ch.length;\n        \n        int low = 0;\n        int high = n - 1;\n        \n        while(low <= high) {\n            int mid = low + (high - low) / 2;\n            \n            if(check(nums, ch, mid)) {\n                ans = mid;\n                high = mid - 1;\n            }\n            else {\n                low = mid + 1;\n            }\n        }\n        \n        if(ans != - 1) {\n            return ans + 1;\n        }\n        \n        return ans;\n    }\n    \n    public boolean check(int[] a, int[] ch, int mid) {\n        int n = a.length;\n        int marked = 0;\n        int dec = 0;\n        int[] lastIdx = new int[n];\n        Arrays.fill(lastIdx, -1);\n        \n        for(int i = 0 ; i <= mid ; i++) {\n            lastIdx[ch[i] - 1] = i;\n        }\n        \n        for(int i = 0 ; i < n ; i++) {\n            if(lastIdx[i] == -1) {\n                return false;\n            }\n        }\n        \n        for(int i = 0 ; i <= mid ; i++) {\n            int val = ch[i] - 1;\n            // System.out.println(i + " " + val + " " + lastIdx[val] + " " + dec + " " + marked + " " +a[val]);\n            if(i == lastIdx[val]) {\n                if(a[val] <= dec) {\n                    marked++;\n                    dec -= a[val];\n                }\n            }\n            else {\n                dec++;\n            }\n            // System.out.println(i + " " + val + " " + lastIdx[val] + " " + dec + " " + marked + " " + a[val]);\n            // System.out.println();\n        }\n        \n        return n == marked;\n    }\n}\n```
['Binary Search', 'Binary Tree', 'Java']