Minimum inverting factor in an array

Given an array of n positive integers, the task is to find the minimum inverting factor in the given array.
Inverting factor is defined as the absolute difference between the reverse of any two numbers arri and arrj where i != j.
Note : Trailing zeroes should be ignored while reversing the digits i.e. 1200 becomes 21 when reversed.

Examples:

Input : arr[] = { 56, 20, 47, 93, 45 }
Output : 9
The minimum inverting factor is 9, of the pair (56, 47).



Input : arr[] = { 26, 15, 45, 150 }
Output : 0
The minimum inverting factor is 0, of the pair (15, 150).

A naive approach is to iterate over two loops to find all possible pairs. Reverse both the numbers individually and find their absolute difference. Update the inverting factor (minimum absolute difference) at every step. Time Complexity would be O(N2).

An efficient approach would be to precompute the reverse of each array element and store it in its reversed form only (considering the case of trailing zeroes also). Now, to find the minimum inverting factor, sort the array in non-decreasing order. Since the array is sorted, minimum absolute difference always occurs among any two adjacent numbers.
Below is the implementation of above approach .

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the minimum inverting factor
int findMinimumInvertingFactor(int arr[], int N)
{
    // ans stores the minimum inverting factor
    int ans = INT_MAX;
  
    // Iterate over the loop and convert each
    // array element into its reversed form
    for (int i = 0; i < N; i++) {
        string s;
        int num = arr[i];
  
        // Extract each digit of the number and
        // store it in reverse order
        while (num > 0) {
            s.push_back(num % 10 + '0');
            num /= 10;
        }
  
        // Find the position upto which trailing
        // zeroes occur
        int pos;
        for (pos = 0; pos < s.size(); pos++)
            if (s[pos] != 0)
                break;
  
        // Form the reversed number
        num = 0;
        for (int j = pos; j < s.size(); j++)
            num = num * 10 + (s[j] - '0');
        arr[i] = num;
    }
    sort(arr, arr + N);
  
    // Consider all adjacent pairs and update the
    // answer accordingly
    for (int i = 1; i < N; i++)
        ans = min(ans, abs(arr[i] - arr[i - 1]));
  
    return ans;
}
  
// Driver Code
int main()
{
    int arr[] = { 56, 20, 47, 93, 45 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    cout << findMinimumInvertingFactor(arr, N) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the above approach
import java.util.*;
  
class GFG
{
      
// Function to find the minimum inverting factor
static int findMinimumInvertingFactor(int arr[], int N)
{
    // ans stores the minimum inverting factor
    int ans = Integer.MAX_VALUE;
  
    // Iterate over the loop and convert each
    // array element into its reversed form
    for (int i = 0; i < N; i++)
    {
        String s = "";
        int num = arr[i];
  
        // Extract each digit of the number and
        // store it in reverse order
        while (num > 0)
        {
            s+=(char)((num % 10) + '0');
            num /= 10;
        }
  
        // Find the position upto which trailing
        // zeroes occur
        int pos;
        for (pos = 0; pos < s.length(); pos++)
            if (s.charAt(pos) != 0)
                break;
  
        // Form the reversed number
        num = 0;
        for (int j = pos; j < s.length(); j++)
            num = num * 10 + (s.charAt(j) - '0');
        arr[i] = num;
    }
    Arrays.sort(arr);
  
    // Consider all adjacent pairs and update the
    // answer accordingly
    for (int i = 1; i < N; i++)
        ans = Math.min(ans, Math.abs(arr[i] - arr[i - 1]));
  
    return ans;
}
  
// Driver Code
public static void main(String[] args) 
{
    int arr[] = { 56, 20, 47, 93, 45 };
    int N = arr.length;
  
    System.out.println(findMinimumInvertingFactor(arr, N));
}
}
  
// This code contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the above approach
  
import sys
  
# Function to find the minimum inverting factor 
def findMinimumInvertingFactor(arr, N) :
      
    # ans stores the minimum inverting factor 
    ans = sys.maxsize
  
    # Iterate over the loop and convert each 
    # array element into its reversed form 
    for i in range(N) :
        num = arr[i] 
        s = ""
  
        # Extract each digit of the number and 
        # store it in reverse order 
        while (num > 0) :
            s += str(num % 10)
            num //= 10 
           
  
        # Find the position upto which trailing 
        # zeroes occur 
        for pos in range(len(s)) : 
            if (s[pos] != "0") :
                break
  
        # Form the reversed number 
        num = 0
        for j in range(pos, len(s)) : 
            num = num * 10 + (ord(s[j]) - ord("0"))
        arr[i] = num
       
    arr.sort()
    # Consider all adjacent pairs and update the 
    # answer accordingly 
    for i in range(N) :
        ans = min(ans, abs(arr[i] - arr[i - 1]))
  
    return ans 
   
  
# Driver Code 
if __name__ == "__main__" :
  
    arr= [ 56, 20, 47, 93, 45 ]
    N = len(arr)
      
    print(findMinimumInvertingFactor(arr, N))
  
# This code is contributed by Ryuga

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System; 
  
class GFG
{
      
// Function to find the minimum inverting factor
static int findMinimumInvertingFactor(int []arr, int N)
{
    // ans stores the minimum inverting factor
    int ans = int.MaxValue;
  
    // Iterate over the loop and convert each
    // array element into its reversed form
    for (int i = 0; i < N; i++)
    {
        String s = "";
        int num = arr[i];
  
        // Extract each digit of the number and
        // store it in reverse order
        while (num > 0)
        {
            s+=(char)((num % 10) + '0');
            num /= 10;
        }
  
        // Find the position upto which trailing
        // zeroes occur
        int pos;
        for (pos = 0; pos < s.Length;pos++)
            if (s[pos] != 0)
                break;
  
        // Form the reversed number
        num = 0;
        for (int j = pos; j < s.Length; j++)
            num = num * 10 + (s[j] - '0');
        arr[i] = num;
    }
    Array.Sort(arr);
  
    // Consider all adjacent pairs and update the
    // answer accordingly
    for (int i = 1; i < N; i++)
        ans = Math.Min(ans, Math.Abs(arr[i] - arr[i - 1]));
  
    return ans;
}
  
// Driver Code
public static void Main(String[] args) 
{
    int []arr = { 56, 20, 47, 93, 45 };
    int N = arr.Length;
  
    Console.WriteLine(findMinimumInvertingFactor(arr, N));
}
}
  
/* This code contributed by PrinciRaj1992 */

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation of the above approach
  
// Function to find the minimum inverting factor
function findMinimumInvertingFactor($arr, $N)
{
    // ans stores the minimum inverting factor
    $ans = PHP_INT_MAX;
  
    // Iterate over the loop and convert each
    // array element into its reversed form
    for ($i = 0; $i < $N; $i++)
    {
        $s="";
        $num = $arr[$i];
  
        // Extract each digit of the number and
        // store it in reverse order
        while ($num > 0) 
        {
            $s.=chr($num % 10 + ord('0'));
            $num =(int)($num/10);
        }
  
        // Find the position upto which trailing
        // zeroes occur
        for ($pos = 0; $pos < strlen($s); $pos++)
            if ($s[$pos] != 0)
                break;
  
        // Form the reversed number
        $num = 0;
        for ($j = $pos; $j < strlen($s); $j++)
            $num = $num * 10 + (ord($s[$j]) - ord('0'));
        $arr[$i] = $num;
    }
    sort($arr);
  
    // Consider all adjacent pairs and update the
    // answer accordingly
    for ($i = 1; $i < $N; $i++)
        $ans = min($ans, abs($arr[$i] - $arr[$i - 1]));
  
    return $ans;
}
  
// Driver Code
  
$arr = array( 56, 20, 47, 93, 45 );
$N = count($arr);
  
echo findMinimumInvertingFactor($arr, $N)."\n";
  
// This code is contributed by mits
?>

chevron_right


Output:

9

Time Complexity : O(N * logN)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.