El entero no negativo faltante más pequeño hasta cada índice de array

Dada una array arr[] de tamaño N , la tarea es para cada índice de array encontrar el entero no negativo faltante más pequeño hasta ese índice de la array dada.

Ejemplos:

Entrada: arr[] = {1, 3, 0, 2}
Salida: 0 0 2 4
Explicación:
El entero no negativo faltante más pequeño del índice 0 a 0 es 0.
El entero no negativo faltante más pequeño del índice 0 a 1 es 0 El entero
no negativo faltante más pequeño del índice 0 a 2 es 2.
El entero no negativo faltante más pequeño del índice 0 a 3 es 4.

Entrada: arr[] = {0, 1, 2, 3, 5}
Salida: 1 2 3 4 4

 

Enfoque: Este problema se puede resolver usando Hashing . Siga los pasos a continuación para resolver el problema:

  • Inicialice una variable, digamos smNonNeg para almacenar los enteros no negativos faltantes más pequeños entre el índice de inicio y el índice actual de la array dada.
  • Inicialice una array, diga hash [N] para verificar si smNonNeg está presente entre el índice de inicio y el índice actual o no.
  • Recorra la array dada y verifique si hash[smNonNeg] es igual a 0 o no. Si se encuentra que es cierto, imprima el valor de smNonNeg .
  • De lo contrario, incremente el valor de smNonNeg mientras que hash[smNonNeg] no sea igual a 0 .

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the smallest
// missing non-negative integer
// up to every array indices
void smlstNonNeg(int arr[], int N)
{
    // Stores the smallest missing
    // non-negative integers between
    // start index to current index
    int smNonNeg = 0;
 
    // Store the boolean value to check
    // smNonNeg present between start
    // index to each index of the array
    bool hash[N + 1] = { 0 };
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Since output always lies
        // in the range[0, N - 1]
        if (arr[i] >= 0 and arr[i] < N) {
            hash[arr[i]] = true;
        }
 
        // Check if smNonNeg is
        // present between start index
        // and current index or not
        while (hash[smNonNeg]) {
            smNonNeg++;
        }
 
        // Print smallest missing
        // non-negative integer
        cout << smNonNeg << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    smlstNonNeg(arr, N);
}

Java

// Java program to implement
// the above approach
import java.io.*;
import java.util.Arrays;
 
class GFG{
  
// Function to print the smallest
// missing non-negative integer
// up to every array indices
static void smlstNonNeg(int arr[], int N)
{
     
    // Stores the smallest missing
    // non-negative integers between
    // start index to current index
    int smNonNeg = 0;
  
    // Store the boolean value to check
    // smNonNeg present between start
    // index to each index of the array
    Boolean[] hash = new Boolean[N + 1];
    Arrays.fill(hash, false);
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Since output always lies
        // in the range[0, N - 1]
        if (arr[i] >= 0 && arr[i] < N)
        {
            hash[arr[i]] = true;
        }
  
        // Check if smNonNeg is
        // present between start index
        // and current index or not
        while (hash[smNonNeg])
        {
            smNonNeg++;
        }
  
        // Print smallest missing
        // non-negative integer
        System.out.print(smNonNeg + " ");
    }
}
  
// Driver Code
public static void main (String[] args)
{
    int arr[] = { 0, 1, 2, 3, 5 };
    int N = arr.length;
     
    smlstNonNeg(arr, N);
}
}
 
// This code is contributed by sanjoy_62

Python3

# Python3 program to implement
# the above approach
 
# Function to print smallest
# missing non-negative integer
# up to every array indices
def smlstNonNeg(arr, N):
     
    # Stores the smallest missing
    # non-negative integers between
    # start index to current index
    smNonNeg = 0
 
    # Store the boolean value to check
    # smNonNeg present between start
    # index to each index of the array
    hash = [0] * (N + 1)
 
    # Traverse the array
    for i in range(N):
 
        # Since output always lies
        # in the range[0, N - 1]
        if (arr[i] >= 0 and arr[i] < N):
            hash[arr[i]] = True
 
        # Check if smNonNeg is
        # present between start index
        # and current index or not
        while (hash[smNonNeg]):
            smNonNeg += 1
 
        # Print smallest missing
        # non-negative integer
        print(smNonNeg, end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 0, 1, 2, 3, 5 ]
    N = len(arr)
     
    smlstNonNeg(arr, N)
 
# This code is contributed by mohit kumar 29

C#

// C# program to implement
// the above approach
using System;
  
class GFG{
   
// Function to print the smallest
// missing non-negative integer
// up to every array indices
static void smlstNonNeg(int[] arr, int N)
{
     
    // Stores the smallest missing
    // non-negative integers between
    // start index to current index
    int smNonNeg = 0;
   
    // Store the boolean value to check
    // smNonNeg present between start
    // index to each index of the array
    bool[] hash = new bool[N + 1];
     
    for(int i = 0; i < N; i++)
    {
        hash[i] = false;
    }
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Since output always lies
        // in the range[0, N - 1]
        if (arr[i] >= 0 && arr[i] < N)
        {
            hash[arr[i]] = true;
        }
   
        // Check if smNonNeg is
        // present between start index
        // and current index or not
        while (hash[smNonNeg])
        {
            smNonNeg++;
        }
   
        // Print smallest missing
        // non-negative integer
        Console.Write(smNonNeg + " ");
    }
}
   
// Driver Code
public static void Main ()
{
    int[] arr = { 0, 1, 2, 3, 5 };
    int N = arr.Length;
      
    smlstNonNeg(arr, N);
}
}
 
// This code is contributed by code_hunt

Javascript

<script>
 
// Javascript program to implement
// the above approach
 
// Function to print the smallest
// missing non-negative integer
// up to every array indices
function smlstNonNeg(arr, N)
{
     
    // Stores the smallest missing
    // non-negative integers between
    // start index to current index
    let smNonNeg = 0;
    
    // Store the boolean value to check
    // smNonNeg present between start
    // index to each index of the array
    let hash = [];
      
    for(let i = 0; i < N; i++)
    {
        hash[i] = false;
    }
      
    // Traverse the array
    for(let i = 0; i < N; i++)
    {
          
        // Since output always lies
        // in the range[0, N - 1]
        if (arr[i] >= 0 && arr[i] < N)
        {
            hash[arr[i]] = true;
        }
    
        // Check if smNonNeg is
        // present between start index
        // and current index or not
        while (hash[smNonNeg])
        {
            smNonNeg++;
        }
    
        // Print smallest missing
        // non-negative integer
        document.write(smNonNeg + " ");
    }
}
 
// Driver Code
let arr = [ 0, 1, 2, 3, 5 ];
let N = arr.length;
   
smlstNonNeg(arr, N);
 
// This code is contributed by target_2   
 
</script>
Producción: 

1 2 3 4 4

 

Complejidad temporal: O(N)
Espacio auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por se_prashant y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *