JAVA SOLUTION [2MS]
\nimport java.util.Arrays;\n\nclass Solution {\n    \n    // Function to check if the given changes are valid\n    boolean cansolve(int nums[], int ind, int cha
```\nimport java.util.Arrays;\n\nclass Solution {\n    \n    // Function to check if the given changes are valid\n    boolean cansolve(int nums[], int ind, int change[]) {\n        // Array to store the last occurrence of each element\n        int last[] = new int[nums.length];\n        Arrays.fill(last, -1);\n        \n        // Fill the last array with indices of elements in the change array\n        for (int i = 0; i <= ind; i++) {\n            last[change[i] - 1] = i;\n        }\n        \n        // Variables to track operations and marked elements\n        int op = 0;\n        int marked = 0;\n        \n        // Iterate through the changes array\n        for (int i = 0; i <= ind; i++) {\n            // If the current change is the last occurrence of its element\n            if (last[change[i] - 1] == i) {\n                // If there are enough operations available to mark this element\n                if (op >= nums[change[i] - 1]) {\n                    op -= nums[change[i] - 1];\n                    marked++;\n                } else {\n                    return false; // Not enough operations available\n                }\n            } else {\n                op++; // Increment operations for non-marked elements\n            }\n        }\n        // Check if all elements are marked\n        return marked == nums.length;\n    }\n    \n    // Binary search to find the earliest second to mark indices\n    int solve(int l, int r, int ans, int nums[], int change[]) {\n        if (l > r) {\n            return ans;\n        }\n        int mid = l + (r - l) / 2;\n        if (cansolve(nums, mid, change)) {\n            return solve(l, mid - 1, mid, nums, change); // Recur for left half\n        } else {\n            return solve(mid + 1, r, ans, nums, change); // Recur for right half\n        }\n    }\n    \n    // Main function to find the earliest second to mark indices\n    public int earliestSecondToMarkIndices(int[] nums, int[] change) {\n        int k = solve(0, change.length - 1, -1, nums, change);\n        return k == -1 ? -1 : k + 1;\n    }\n}\n```\n
['Greedy', 'Binary Tree', 'Java']