Print digit’s position to be removed to make a number divisible by 6

Given a number N, remove exactly one digit to make the number divisible by 6 (make it the largest possible). Print the position that has to be removed, If not possible then print -1.

Examples:

Input: 123
Output: 3 
Explanation: Remove 3rd position element and 
hence the number is 12, which is divisible
by 6 and is the greatest possible.

Input: 134
Output: -1
Explanation: Not possible to remove any and 
make it divisible by 6.

Input: 4510222
Output: 1 
Explanation: Remove either 4 or 1 to make it 
divisible by 6. The numbers after removing 4
and 1 are 510222 and 450222 respectively.
So, remove 1st position to make it the
greatest possible.



Naive Approach:
Traverse for every element and check if by subtracting it the number is divisible by 6 or not and then store the max possible number. This won’t work when N is a very large number whose divisibility cannot be checked by % operator. It will only work for smaller N.

Efficient Approach:
Take the input as a string and think of the possible cases. You can check any larger number’s divisibility by 6 if it is divisible by 2 and 3, then it is divisible by 6 also. The two cases that will arise are :-

1) When the unit’s digit is odd
When the last digit is odd, the only possible way is to remove the last digit to make it divisible by 6. So remove the last digit and check if the sum % 3 == 0 to make sure that after removing the last digit, the second last digit of N is even and its sum % 3 == 0, then you get your answer as Nth position that has to be removed. If any of the cases fail, then you cannot remove any digit to make it divisible by 6.

2) When the unit’s digit is even
In this case, multiple choices are there. Let sum be sum of digits of given number. We can delete any digit d (except unit place digit if ten’s place digit is odd, so that the number remains a multiple of 2) for which sum % 3 == d % 3. This works because after deleting that digit, sum is a multiple of 3.

Now, to maximize this number, we need to find the digit at largest place satisfying above condition.
Examples:
1. Number = 4510222
sum of digits = 4 + 5 + 1 + 2 + 2 + 2 = 16
sum % 3 = 1

Now, we can delete digits 1 and 4 (because 1 % 3 = 3 and 4 % 3 = 1)
If we delete 1, we get number 450222. If we delete 4, we get number 510222

We delete the largest digit (leftmost) for which the next digit is greater than deleted digit.

2. Number = 7510222
sum of digits = 7 + 5 + 1 + 0 + 2 + 2 + 2 = 19
sum % 3 = 1
Digits 7 and 1 can be deleted according to above solution, giving numbers 510222 and 750222 respectively. Here, deleting largest (leftmost) index give smaller result because 7 > 5. This worked in above case because 4 < 5.

Correct Solution:
Find leftmost digit satisfying both the constraints

1. sum % 3 == digit % 3
2. digit < Immediate next digit


If you can’t maximize the addition of something, try to minimize it’s reduction. In case no digit is found such that digit is less than Immediate right digit than follow the above approach. If you remove something from right, the number will be the maximum possible as you are removing the lowest place value digit.

Once done print the index if any such element is found else simply print -1.

Below is the implementation of above approach:-

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to print digit's position
// to be removed to make number
// divisible by 6
#include <bits/stdc++.h>
using namespace std;
  
// function to print the number divisible
// by 6 after exactly removing a digit
void greatest(string s)
{
    int n = s.length();
    int a[n];
  
    // stores the sum of all elements
    int sum = 0;
  
    // traverses the string and converts
    // string to number array and sums up
    for (int i = 0; i < n; i++) {
        a[i] = s[i] - '0';
        sum += a[i];
    }
  
    if (a[n - 1] % 2) // ODD CHECK
    {
        // if second last is odd or
        // sum of n-1 elements are not
        // divisible by 3.
        if (a[n - 2] % 2 != 0 or (sum - a[n - 1]) % 3 != 0) {
            cout << "-1" << endl;
        }
  
        // second last is even and
        // print n-1 elements
        // removing last digit
        else {
      
            // last digit removed
            cout << n << endl;
        }
    }
    else {
        int re = sum % 3;
        int del = -1;
  
        // counter to check if any
        // element after removing,
        // its sum%3==0
        int flag = 0;
  
        // traverse till second last element
        for (int i = 0; i < n - 1; i++) {
  
            // to check if any element
            // after removing,
            // its sum%3==0
            if ((a[i]) % 3 == re) {
      
                // the leftmost element
                if (a[i + 1] > a[i]) {
                    del = i;
                    flag = 1;
  
                    // break at the leftmost
                    // element
                    break;
                }
                else {
                    // stores the right most
                    // element
                    del = i;
                }
            }
        }
  
        // if no element has been found
        // as a[i+1]>a[i]
        if (flag == 0) {
      
            // if second last is even, then
            // remove last if (sum-last)%3==0
            if (a[n - 2] % 2 == 0 and re == a[n - 1] % 3)
                del = n - 1;
        }
  
        // if no element which on removing
        // gives sum%3==0
        if (del == -1)
            cout << -1 << endl;
        else {
            cout << del + 1 << endl;
        }
    }
}
  
// driver program to test the above function
int main()
{
    string s = "7510222";
    greatest(s);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print digit's position
// to be removed to make number
// divisible by 6
import java.util.*;
  
class solution
{
  
// function to print the number divisible
// by 6 after exactly removing a digit
static void greatest(String s)
{
    int n = s.length();
    int[] a = new int[n];
  
    // stores the sum of all elements
    int sum = 0;
  
    // traverses the string and converts
    // string to number array and sums up
    for (int i = 0; i < n; i++) 
    {
        a[i] = s.charAt(i) - '0';
        sum += a[i];
    }
  
    if (a[n - 1] % 2 !=0) // ODD CHECK
    {
        // if second last is odd or
        // sum of n-1 elements are not
        // divisible by 3.
        if (a[n - 2] % 2 != 0 || (sum - a[n - 1]) % 3 != 0)
        {
            System.out.println("-1");
        }
  
        // second last is even and
        // print n-1 elements
        // removing last digit
        else
        {
      
            // last digit removed
            System.out.println(n);
        }
    }
      
    else 
    {
        int re = sum % 3;
        int del = -1;
  
        // counter to check if any
        // element after removing,
        // its sum%3==0
        int flag = 0;
  
        // traverse till second last element
        for (int i = 0; i < n - 1; i++) 
        {
  
            // to check if any element
            // after removing,
            // its sum%3==0
            if ((a[i]) % 3 == re)
            {
      
                // the leftmost element
                if (a[i + 1] > a[i])
                {
                    del = i;
                    flag = 1;
  
                    // break at the leftmost
                    // element
                    break;
                }
                else
                {
                    // stores the right most
                    // element
                    del = i;
                }
            }
        }
  
        // if no element has been found
        // as a[i+1]>a[i]
        if (flag == 0
        {
      
            // if second last is even, then
            // remove last if (sum-last)%3==0
            if (a[n - 2] % 2 == 0 && re == a[n - 1] % 3)
                del = n - 1;
        }
  
        // if no element which on removing
        // gives sum%3==0
        if (del == -1)
        System.out.println(-1);
        else 
        {
        System.out.println(del + 1);
        }
    }
}
  
// driver program to test the above function
public static void main(String args[])
{
    String s = "7510222";
    greatest(s);
      
}
}
  
//This code is contributed by
//Surendra_Gangwar

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to print digit's position
# to be removed to make number
# divisible by 6
import math as mt 
  
# function to print the number divisible
# by 6 after exactly removing a digit
def greatest(s):
  
    n = len(s)
    a=[0 for i in range(n)]
   
    # stores the Sum of all elements
    Sum = 0
   
    # traverses the string and converts
    # string to number array and Sums up
    for i in range(n): 
        a[i] = ord(s[i]) - ord('0')
        Sum += a[i]
      
   
    if (a[n - 1] % 2): # ODD CHECK
      
        # if second last is odd or
        # Sum of n-1 elements are not
        # divisible by 3.
        if (a[n - 2] % 2 != 0 or (Sum - a[n - 1]) % 3 != 0):
            print("-1")
              
          
        # second last is even and
        # prn-1 elements
        # removing last digit
        else
       
            # last digit removed
            print(n)
          
      
    else:
        re = Sum % 3
        dell = -1
   
        # counter to check if any
        # element after removing,
        # its Sum%3==0
        flag = 0
   
        # traverse till second last element
        for i in range(n-1): 
   
            # to check if any element
            # after removing,
            # its Sum%3==0
            if ((a[i]) % 3 == re):
       
                # the leftmost element
                if (a[i + 1] > a[i]):
                    dell = i
                    flag = 1
   
                    # break at the leftmost
                    # element
                    break
                  
                else:
                    # stores the right most
                    # element
                    dell = i
                  
              
          
   
        # if no element has been found
        # as a[i+1]>a[i]
        if (flag == 0):
       
            # if second last is even, then
            # remove last if (Sum-last)%3==0
            if (a[n - 2] % 2 == 0 and re == a[n - 1] % 3):
                dell = n - 1
          
   
        # if no element which on removing
        # gives Sum%3==0
        if (dell == -1):
            print("-1")
        else:
            print(dell + 1)
          
      
  
   
# driver program to test the above function
  
s = "7510222"
greatest(s)
  
#This code is contributed by Mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print digit's position
// to be removed to make number
// divisible by 6
using System;
  
class GFG
{
  
// function to print the number divisible
// by 6 after exactly removing a digit
static void greatest(string s)
{
    int n = s.Length;
    int[] a = new int[n];
  
    // stores the sum of all elements
    int sum = 0;
  
    // traverses the string and converts
    // string to number array and sums up
    for (int i = 0; i < n; i++) 
    {
        a[i] = s[i] - '0';
        sum += a[i];
    }
  
    if (a[n - 1] % 2 != 0) // ODD CHECK
    {
        // if second last is odd or
        // sum of n-1 elements are not
        // divisible by 3.
        if (a[n - 2] % 2 != 0 || 
           (sum - a[n - 1]) % 3 != 0)
        {
            Console.Write("-1");
        }
  
        // second last is even and
        // print n-1 elements
        // removing last digit
        else
        {
      
            // last digit removed
            Console.Write(n);
        }
    }
      
    else
    {
        int re = sum % 3;
        int del = -1;
  
        // counter to check if any
        // element after removing,
        // its sum%3==0
        int flag = 0;
  
        // traverse till second last element
        for (int i = 0; i < n - 1; i++) 
        {
  
            // to check if any element
            // after removing,
            // its sum%3==0
            if ((a[i]) % 3 == re)
            {
      
                // the leftmost element
                if (a[i + 1] > a[i])
                {
                    del = i;
                    flag = 1;
  
                    // break at the leftmost
                    // element
                    break;
                }
                else
                {
                    // stores the right most
                    // element
                    del = i;
                }
            }
        }
  
        // if no element has been found
        // as a[i+1]>a[i]
        if (flag == 0) 
        {
      
            // if second last is even, then
            // remove last if (sum-last)%3==0
            if (a[n - 2] % 2 == 0 && 
                  re == a[n - 1] % 3)
                del = n - 1;
        }
  
        // if no element which on removing
        // gives sum%3==0
        if (del == -1)
        Console.Write(-1);
        else
        {
        Console.Write(del + 1);
        }
    }
}
  
// Driver Code
public static void Main()
{
    string s = "7510222";
    greatest(s);
}
}
  
// This code is contributed 
// by ChitraNayal

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to print digit's position
// to be removed to make number
// divisible by 6
  
// Function to print the number divisible
// by 6 after exactly removing a digit
function greatest($s)
{
    $n = strlen($s);
    $a[$n] = array();
  
    // stores the sum of all elements
    $sum = 0;
  
    // traverses the string and converts
    // string to number array and sums up
    for ($i = 0; $i < $n; $i++)
    {
        $a[$i] = $s[$i] - '0';
        $sum += $a[$i];
    }
  
    if ($a[$n - 1] % 2) // ODD CHECK
    {
        // if second last is odd or
        // sum of n-1 elements are not
        // divisible by 3.
        if ($a[$n - 2] % 2 != 0 or 
           ($sum - $a[$n - 1]) % 3 != 0) 
        {
            echo "-1" ,"\n";
        }
  
        // second last is even and print n-1 
        // elements removing last digit
        else 
        {
      
            // last digit removed
            echo $n, "\n";
        }
    }
    else 
    {
        $re = $sum % 3;
        $del = -1;
  
        // counter to check if any
        // element after removing,
        // its sum%3==0
        $flag = 0;
  
        // traverse till second last element
        for ($i = 0; $i < $n - 1; $i++) 
        {
  
            // to check if any element
            // after removing, its sum%3==0
            if (($a[$i]) % 3 == $re
            {
      
                // the leftmost element
                if ($a[$i + 1] > $a[$i])
                {
                    $del = $i;
                    $flag = 1;
  
                    // break at the leftmost
                    // element
                    break;
                }
                else
                {
                    // stores the right most
                    // element
                    $del = $i;
                }
            }
        }
  
        // if no element has been found
        // as a[i+1]>a[i]
        if ($flag == 0)
        {
      
            // if second last is even, then
            // remove last if (sum-last)%3==0
            if ($a[$n - 2] % 2 == 0 and 
                $re == $a[$n - 1] % 3)
                $del = $n - 1;
        }
  
        // if no element which on removing
        // gives sum%3==0
        if ($del == -1)
            echo -1, "\n";
        else
        {
            echo $del + 1, "\n";
        }
    }
}
  
// Driver Code
$s = "7510222";
greatest($s);
      
// This code is contributed by ajit
?>

chevron_right



Output:

3

Time Complexity: O(no of digits)



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.