Minimum deletion such that XOR of adjacent digits is atmost 1


In this problem, we will learn to find the count of minimum deletion required so that when we take the XOR of any two adjacent elements, we should either get 0 or 1.

We will use the properties of the XOR operations to solve the problem. For example, when we take XOR of the same numbers, we always get 0; when we take XOR of the consecutive even and odd number, we get 1.

Problem Statement

We have given a num_str string containing the numeric digits. We need to count the minimum deletions required so that the XOR of any adjacent remaining digits should be at most 1.

Sample Examples

Input: num_str = "454545";
Output: 0

Explanation

The XOR operation of any two adjacent digits in the given string is 1. So we don’t need to delete any digits.

Sample Examples

Input: num_str = "7775477";
Output: 2

Explanation

We need to delete ‘54’ from the string. So, when we take the XOR of any two adjacent digits from ‘77777’, we get either 0 or 1.

Sample Examples

Input: num_str = "5556767675"
Output: 4

Explanation

Here, we have two options. The first is when we take the XOR of any adjacent digit in the ‘5555’ string, we get 0. So, we need to delete ‘676767’.

Another option is when we take the XOR of any two adjacent digits in the ‘676767’ string, we get 1. So, we need to delete the ‘5555’ string.

We have chosen the minimum number of deletions which is 4.

Approach 1

In this approach, we will keep either all the same digits or a pair of even and odd consecutive digits based on the minimum deletion required.

So, we will keep only valid digits and delete all other digits.

Algorithm

  • Step 1 − Define the ‘freq’ map to store the string character and its frequency.

  • Step 2 − Traverse the string and store the frequency of each character in the map.

  • Step 3 − Initialize the ‘validNums’ variable with 0 to store the number of valid digits.

  • Step 4 − Start traversing the frequency map. If the digit is divisible by 2, and the next digit also exists in the map, update the ‘validNums’ value with the maximum value from ‘validNums’ and the sum of current and next digit frequencies.

  • Step 5 − If the current digit is not divisible by 2, update the validNums variable’s value with the maximum of ‘validNums’ and frequency of the second digit.

  • Step 6 − Return the resultant value after subtracting the ‘validNums’ variable’s value from the string length.

Example

Following are the programs to the above algorithm −

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int totalDeletions(char *num_str) {
   // To store the frequency of each digit
   int freq[10] = {0};
    
   // Calculating the frequency of each digit
   for (int p = 0; p < strlen(num_str); p++) {
      freq[num_str[p] - '0']++;
   }
   int validNums = 0;
    
   // Traversing the frequency array
   for (int i = 0; i < 10; i++) {
      // If the digit is even, create a pair of (digit, digit+1)
      if (i % 2 == 0) {
         // Update the validNums with the maximum of validNums and (freq of digit + freq of digit+1)
         if (i + 1 < 10) {
            validNums = (validNums > (freq[i] + freq[i + 1])) ? validNums : (freq[i] + freq[i + 1]);
         }
      }
      // Update the validNums with the maximum of validNums and freq of digit
      validNums = (validNums > freq[i]) ? validNums : freq[i];
   }
    
   // Return the minimum number of deletions required
   return strlen(num_str) - validNums;
}
int main() {
    char num_str[] = "454545";
    printf("The total number of deletions required to get at most when we take XOR of all digits is %d\n", totalDeletions(num_str));
    return 0;
}

Output

The total number of deletions required to get at most when we take XOR of all digits is 0
#include <bits/stdc++.h>
using namespace std;

int totalDeletions(string num_str){
   // To store the frequency of each digit
   unordered_map<int, int> freq;
   
   // Calculating the frequency of each digit
   for (int p = 0; p < num_str.size(); p++)    {
      freq[num_str[p]]++;
   }
   int validNums = 0;
   
   // Traversing the map
   for (auto p : freq) {
   
      // If the digit is even, create pair of (digit, digit+1)
      if ((p.first - '0') % 2 == 0) {
      
         // Update the validNums with the maximum of validNums and (freq of digit + freq of digit+1)
         if (freq.find(p.first + 1) != freq.end()){
            validNums = max(validNums, (p.second + freq[p.first + 1]));
         }
      }
      
      // Update the validNums with the maximum of validNums and freq of digit
      validNums = max(validNums, p.second);
   }
   
   // Return the minimum number of deletions required
   return num_str.size() - validNums;
}
int main(){
   string num_str = "454545";
   cout << "The total number of deletions required to get atmost when we take XOR of all digits is " << totalDeletions(num_str);
   return 0;
}

Output

The total number of deletions required to get at most when we take XOR of all digits is 0
import java.util.HashMap;

public class Main {
   public static int totalDeletions(String num_str) {
      // To store the frequency of each digit
      HashMap<Integer, Integer> freq = new HashMap<>();
      
      // Calculating the frequency of each digit
      for (int p = 0; p < num_str.length(); p++) {
         int digit = Character.getNumericValue(num_str.charAt(p));
         freq.put(digit, freq.getOrDefault(digit, 0) + 1);
      }
      int validNums = 0;
      
      // Traversing the map
      for (int digit : freq.keySet()) {
         // If the digit is even, create a pair of (digit, digit+1)
         if (digit % 2 == 0) {
            // Update the validNums with the maximum of validNums and (freq of digit + freq of digit+1)
            if (freq.containsKey(digit + 1)) {
               validNums = Math.max(validNums, freq.get(digit) + freq.get(digit + 1));
            }
         }
         // Update the validNums with the maximum of validNums and freq of digit
         validNums = Math.max(validNums, freq.get(digit));
      }
        
      // Return the minimum number of deletions required
      return num_str.length() - validNums;
   }

   public static void main(String[] args) {
      String num_str = "454545";
      System.out.println("The total number of deletions required to get at most when we take XOR of all digits is " + totalDeletions(num_str));
   }
}

Output

The total number of deletions required to get at most when we take XOR of all digits is 0
def total_deletions(num_str):
   # To store the frequency of each digit
   freq = {}
   
   # Calculating the frequency of each digit
   for digit in num_str:
      freq[digit] = freq.get(digit, 0) + 1
   
   valid_nums = 0
   
   # Traversing the map
   for digit, count in freq.items():
      # If the digit is even, create a pair of (digit, digit+1)
      if int(digit) % 2 == 0:
         # Update the validNums with the maximum of validNums and (freq of digit + freq of digit+1)
         if str(int(digit) + 1) in freq:
            valid_nums = max(valid_nums, count + freq[str(int(digit) + 1)])
      
      # Update the validNums with the maximum of validNums and freq of digit
      valid_nums = max(valid_nums, count)
    
   # Return the minimum number of deletions required
   return len(num_str) - valid_nums

num_str = "454545"
print(f"The total number of deletions required to get at most when we take XOR of all digits is {total_deletions(num_str)}")

Output

The total number of deletions required to get at most when we take XOR of all digits is 0

Time complexity − O(N) for traversing the string.

Space complexity − O(1), as we always need to use the map to only store the frequency of 10 digits.

Sometimes, we should have knowledge of the properties of the particular operations to solve the problem, as we used the XOR properties in this example. Programmers should remember that the XOR of the same number is always zero.

Updated on: 27-Oct-2023

57 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements