Similar Problems

Similar Problems not available

Smallest Missing Non Negative Integer After Operations - Leetcode Solution

Companies:

LeetCode:  Smallest Missing Non Negative Integer After Operations Leetcode Solution

Difficulty: Medium

Topics: greedy hash-table math array  

Problem:

Given an array A of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

You can currently jump up to a maximum of K steps.

In each step, you can do one of the following:

  • Jump with the maximum jump length at your current position.
  • Choose any index (including your current position) and play with the value of A in that index such that A[i] = A[i] - 1.

What is the smallest missing non-negative integer that you cannot reach at any point?

Solution:

To solve the problem, we can start by initializing a set containing all the integers from 0 to n-1, where n is the length of the input array A.

Then, we can perform a BFS on the set, where at each step we can either jump to a new index using the given jump length, or reduce the value of A[i] by 1, which corresponds to reducing our jump length by 1.

If we reach an index that is not in the set, we update the answer to be the smallest missing non-negative integer.

Here's the Python code that implements the above approach:

from typing import List

class Solution:
    def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:

        n = len(parents)
        graph = [[] for _ in range(n)]
        for i in range(1, n):
            graph[parents[i]].append(i)

        ans = [1] * n
        seen = set()

        def dfs(node):
            if not nums[node] in seen:
                seen.add(nums[node])
                while ans[node] in seen:
                    ans[node] += 1
            for child in graph[node]:
                dfs(child)

        dfs(0)
        return ans

The time complexity of the above approach is O(nlogn) due to the use of set operations, where n is the length of the input array A. The space complexity is also O(n) due to the use of the set.

Smallest Missing Non Negative Integer After Operations Solution Code

1