Minimice K cuyo XOR con elementos de array dados deja la array sin cambios

Dada una array de N elementos, la tarea es encontrar el valor mínimo de K tal que Bitwise XOR de K con todos los elementos de la array produzca el mismo conjunto de elementos. Si es imposible encontrar cualquier valor de K , imprima «-1» .

Ejemplos: 

Entrada: arr[] = { 1, 0, 2, 3} 
Salida:
Explicación: 
Para K = 1, 
1 xor 1 = 0
1 xor 0 = 1
1 xor 2 = 3
1 xor 3 = 2
Así, K = 1 es el menor valor positivo posible que deja la array inalterada.

Entrada: arr[] = { 7, 1, 2, 3, 8} 
Salida: -1 

Enfoque ingenuo: el enfoque ingenuo es iterar todos los valores posibles de K en el rango [1, 1024] y verificar si Bitwise XOR de K con todos los elementos en la array da los mismos elementos de la array o no. Si para cualquier valor mínimo de K , Bitwise XOR produce la misma array, imprima ese valor de K ; de lo contrario, imprima «-1» .
Complejidad de Tiempo: O(K*N 2
Espacio Auxiliar: O(1)

Enfoque eficiente: el enfoque anterior se puede optimizar mediante el uso de espacio adicional. A continuación se muestran los pasos: 

  1. Inserte todos los elementos en el conjunto .
  2. Iterar para todos los valores posibles de K en el rango [0, 1024] .
  3. Para cada elemento del conjunto, encuentre su Bitwise XOR con K .
  4. El primer valor de K para el cual todos los elementos generados después de Bitwise XOR con el elemento insertado es el mismo que el del conjunto dado, luego imprima el valor de K .
  5. Si no se obtiene tal K , imprima “-1” .

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

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// value of K in given range
int min_value(int arr[], int N)
{
    int x, X, K;
 
    // Declare a set
    set<int> S;
 
    for (int i = 0; i < N; i++) {
        S.insert(arr[i]);
    }
 
    // Initialize count variable
    int count = 0;
 
    // Iterate in range [1, 1024]
    for (int i = 1; i <= 1024; i++) {
 
        // counter set as 0
        count = 0;
 
        // Iterating through the Set
        for (auto it = S.begin(); it != S.end(); it++)
 
        // Check if the XOR
        // calculated is present
        // in the Set
        {
 
            X = ((i | *it) - (i & *it));
 
            // If the value of Bitwise XOR
            // inside the given set then
            // increment count
            if (S.find(X) != S.end()) {
                count++;
            }
        }
 
        // Check if the value of count is
        // equal to the size of set
        if (count == S.size()) {
            K = i;
 
            // Return minimum value of K
            return K;
        }
    }
 
    // If no such K is found
    return -1;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 0, 3, 3, 0, 2 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << min_value(arr, N);
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to find the minimum
    // value of K in given range
    static int min_value(int arr[], int N)
    {
        int x, X, K;
 
        // Declare a set
        HashSet<Integer> S = new HashSet<Integer>();
 
        for (int i = 0; i < N; i++) {
            S.add(arr[i]);
        }
 
        // Initialize count variable
        int count = 0;
 
        // Iterate in range [1, 1024]
        for (int i = 1; i <= 1024; i++) {
 
            // counter set as 0
            count = 0;
 
            // Iterating through the Set
            for (int it : S) {
 
                // Check if the XOR
                // calculated is present
                // in the Set
                X = ((i | it) - (i & it));
 
                // If the value of Bitwise XOR
                // inside the given set then
                // increment count
                if (S.contains(X)) {
                    count++;
                }
            }
 
            // Check if the value of count is
            // equal to the size of set
            if (count == S.size()) {
                K = i;
 
                // Return minimum value of K
                return K;
            }
        }
 
        // If no such K is found
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array
        int arr[] = { 1, 0, 3, 3, 0, 2 };
 
        int N = arr.length;
 
        // Function Call
        System.out.print(min_value(arr, N));
    }
}
 
// This code is contributed by Rajput-Ji

Python3

# Python3 program for the above approach
 
# Function to find the minimum
# value of K in given range
 
 
def min_value(arr, N):
 
    x, X, K = 0, 0, 0
 
    # Declare a set
    S = set()
 
    for i in range(N):
        S.add(arr[i])
 
    # Initialize count variable
    count = 0
 
    # Iterate in range [1, 1024]
    for i in range(1, 1024):
 
        # counter set as 0
        count = 0
 
        # Iterating through the Set
        for it in S:
 
            # Check if the XOR
            # calculated is present
            # in the Set
            X = ((i | it) - (i & it))
 
            # If the value of Bitwise XOR
            # inside the given set then
            # increment count
            if X in S:
                count += 1
 
        # Check if the value of count is
        # equal to the size of set
        if (count == len(S)):
            K = i
 
            # Return minimum value of K
            return K
 
    # If no such K is found
    return -1
 
# Driver Code
 
 
# Given array
arr = [1, 0, 3, 3, 0, 2]
 
N = len(arr)
 
# Function Call
print(min_value(arr, N))
 
# This code is contributed by shubhamsingh10

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Function to find the minimum
    // value of K in given range
    static int min_value(int[] arr, int N)
    {
        // int x;
        int X, K;
 
        // Declare a set
        HashSet<int> S = new HashSet<int>();
 
        for (int i = 0; i < N; i++) {
            S.Add(arr[i]);
        }
 
        // Initialize count variable
        int count = 0;
 
        // Iterate in range [1, 1024]
        for (int i = 1; i <= 1024; i++) {
 
            // counter set as 0
            count = 0;
 
            // Iterating through the Set
            foreach(int it in S)
            {
 
                // Check if the XOR
                // calculated is present
                // in the Set
                X = ((i | it) - (i & it));
 
                // If the value of Bitwise XOR
                // inside the given set then
                // increment count
                if (S.Contains(X)) {
                    count++;
                }
            }
 
            // Check if the value of count is
            // equal to the size of set
            if (count == S.Count) {
                K = i;
 
                // Return minimum value of K
                return K;
            }
        }
 
        // If no such K is found
        return -1;
    }
 
    // Driver code
    static void Main()
    {
 
        // Given array
        int[] arr = { 1, 0, 3, 3, 0, 2 };
 
        int N = arr.Length;
 
        // Function call
        Console.Write(min_value(arr, N));
    }
}
 
// This code is contributed by divyeshrabadiya07

Javascript

<script>
// Javascript implementation for the above approach
 
    // Function to find the minimum
    // value of K in given range
    function min_value(arr, N)
    {
        let x, X, K;
 
        // Declare a set
        let S = [];
 
        for (let i = 0; i < N; i++) {
            S.push(arr[i]);
        }
 
        // Initialize count variable
        let count = 0;
 
        // Iterate in range [1, 1024]
        for (let i = 1; i <= 1024; i++) {
 
            // counter set as 0
            count = 0;
 
            // Iterating through the Set
            for (let it in S) {
 
                // Check if the XOR
                // calculated is present
                // in the Set
                X = ((i | it) - (i & it));
 
                // If the value of Bitwise XOR
                // inside the given set then
                // increment count
                for (let j in S) {
                if (S[j]==X) {
                    count++;
                }
                }
            }
 
            // Check if the value of count is
            // equal to the size of set
            if (count == S.length) {
                K = i;
 
                // Return minimum value of K
                return K;
            }
        }
 
        // If no such K is found
        return -1;
    }
 
    // Driver Code
     
    // Given array
        let arr = [ 1, 0, 3, 3, 0, 2 ];
 
        let N = arr.length;
 
        // Function Call
        document.write(min_value(arr, N));
 
</script>
Producción: 

1

 

Complejidad de tiempo: O(K*N*log 2 N) 
Espacio auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por mishrapriyanshu557 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 *