Find a rotation with maximum hamming distance
Given an array of N elements, create a new array which is a rotation of the given array, and hamming distance between both the arrays is maximum. The task is to print the maximized hamming distance between given and new arrays.
Hamming distance between two arrays or strings of equal length is the number of positions at which the corresponding characters (elements) are different.
Examples:
Input: N = 3, arr = {1, 4, 1}
Output: 2
Explanation: Possible rotations of given array = 4 1 1 and 1 1 4. In each case the hamming distance is 2. Therefore the maximum hamming distance will be 2.
Input: N = 4, arr = {2, 4, 8, 0}
Output: 4
Explanation: Among possible rotations of given array, the rotations 8 0 2 4 and 0 2 4 8, have the maximum hamming distance of 4.
Naive Approach:
The idea is to create another array that is double the size of the original array, such that the elements of this new array (copy array) are just the elements of the original array repeated twice in the same sequence. For example, if the original array is 1 4 1, then the copy array is 1 4 1 1 4 1. Now, iterate through the copy array and find hamming distance with every shift (or rotation). So we check 4 1 1, 1 1 4, 1 4 1, and choose the output for which the hamming distance is maximum.
Illustration:
Given array arr[]={2, 4, 6, 8}.
New array brr[]={2, ,4, 6, 8, 2, 4, 6, 8} , count=0
- In first iteration : {2, 4, 6, 8} & {2 ,4, 6, 8, 2, 4, 6, 8} , count=1
- In second iteration : {2, 4, 6, 8} & {2 ,4, 6, 8, 2, 4, 6, 8} , count=2
- In third iteration : {2, 4, 6, 8} & {2 ,4, 6, 8, 2, 4, 6, 8} , count=3
- In fourth iteration : {2, 4, 6, 8} & {2 ,4, 6, 8, 2, 4, 6, 8} , count=4
- count = size of original array, hence output is 4
Implementation:
We will create another array twice the size of the original array and insert the elements in it one by one, twice. Now we will perform rotation on the array and for each rotation, we will check if the value of the original array matches the newly created array.
- If they don’t match we will increase our counter value
- After the value is incremented we will perform a condition to check the max value, to keep a check on the maximum value that can be obtained.
- Else if the values don’t match, we don’t have to perform any operation
- Inside the checking loop, we will also have to keep a check if the value of counter = size of the original array, as it is the maximum value that we can obtain. If the condition matches, we may return the value. This condition optimizes our code.
Below is the code implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxHamming( int arr[], int n)
{
int brr[2 * n + 1];
for ( int i = 0; i < n; i++) {
brr[i] = arr[i];
brr[n + i] = arr[i];
}
int maxHam = 0;
for ( int i = 1; i < n; i++) {
int currHam = 0;
for ( int j = i, k = 0; j < (i + n); j++, k++)
if (brr[j] != arr[k])
currHam++;
if (currHam == n)
return n;
maxHam = max(maxHam, currHam);
}
return maxHam;
}
int main()
{
int arr[] = { 2, 4, 6, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxHamming(arr, n);
return 0;
}
|
C
#include <stdio.h>
int max( int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
int maxHamming( int arr[], int n)
{
int brr[2 * n + 1];
for ( int i = 0; i < n; i++) {
brr[i] = arr[i];
brr[n + i] = arr[i];
}
int maxHam = 0;
for ( int i = 1; i < n; i++) {
int currHam = 0;
for ( int j = i, k = 0; j < (i + n); j++, k++)
if (brr[j] != arr[k])
currHam++;
if (currHam == n)
return n;
maxHam = max(maxHam, currHam);
}
return maxHam;
}
int main()
{
int arr[] = { 2, 4, 6, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "%d\n" , maxHamming(arr, n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int maxHamming( int arr[], int n)
{
int brr[] = new int [ 2 * n + 1 ];
for ( int i = 0 ; i < n; i++) {
brr[i] = arr[i];
brr[n + i] = arr[i];
}
int maxHam = 0 ;
for ( int i = 1 ; i < n; i++) {
int currHam = 0 ;
for ( int j = i, k = 0 ; j < (i + n); j++, k++)
if (brr[j] != arr[k])
currHam++;
if (currHam == n)
return n;
maxHam = Math.max(maxHam, currHam);
}
return maxHam;
}
public static void main(String[] args)
{
int arr[] = { 2 , 4 , 6 , 8 };
int n = arr.length;
System.out.print(maxHamming(arr, n));
}
}
|
Python3
def maxHamming( arr , n ):
brr = [ 0 ] * ( 2 * n + 1 )
for i in range (n):
brr[i] = arr[i]
for i in range (n):
brr[n + i] = arr[i]
maxHam = 0
for i in range ( 1 , n):
currHam = 0
k = 0
for j in range (i, i + n):
if brr[j] ! = arr[k]:
currHam + = 1
k = k + 1
if currHam = = n:
return n
maxHam = max (maxHam, currHam)
return maxHam
arr = [ 2 , 4 , 6 , 8 ]
n = len (arr)
print (maxHamming(arr, n))
|
C#
using System;
class GFG {
static int maxHamming( int []arr, int n)
{
int []brr= new int [2 * n + 1];
for ( int i = 0; i < n; i++){
brr[i] = arr[i];
brr[n+i] = arr[i];
}
int maxHam = 0;
for ( int i = 1; i < n; i++)
{
int currHam = 0;
for ( int j = i, k=0; j < (i + n);
j++, k++)
if (brr[j] != arr[k])
currHam++;
if (currHam == n)
return n;
maxHam = Math.Max(maxHam, currHam);
}
return maxHam;
}
public static void Main ()
{
int []arr = {2, 4, 6, 8};
int n = arr.Length;
Console.Write(maxHamming(arr, n));
}
}
|
PHP
<?php
function maxHamming( $arr , $n )
{
$brr = array ();
for ( $i = 0; $i < $n ; $i ++)
$brr [ $i ] = $arr [ $i ];
for ( $i = 0; $i < $n ; $i ++)
$brr [ $n + $i ] = $arr [ $i ];
$maxHam = 0;
for ( $i = 1; $i < $n ; $i ++)
{
$currHam = 0;
for ( $j = $i , $k = 0; $j < ( $i + $n );
$j ++, $k ++)
if ( $brr [ $j ] != $arr [ $k ])
$currHam ++;
if ( $currHam == $n )
return $n ;
$maxHam = max( $maxHam , $currHam );
}
return $maxHam ;
}
$arr = array (2, 4, 6, 80);
$n = count ( $arr );
echo maxHamming( $arr , $n );
?>
|
Javascript
<script>
function maxHamming(arr, n)
{
let brr = new Array(2 *n + 1);
for (let i = 0; i < n; i++){
brr[i] = arr[i];
brr[n+i] = arr[i];
}
let maxHam = 0;
for (let i = 1; i < n; i++)
{
let currHam = 0;
for (let j = i, k=0; j < (i + n); j++,k++)
if (brr[j] != arr[k])
currHam++;
if (currHam == n)
return n;
maxHam = max(maxHam, currHam);
}
return maxHam;
}
let arr = [2, 4, 6, 8];
let n = arr.length;
document.write(maxHamming(arr, n));
</script>
|
Time Complexity: O(n2), Where n is the size of the given array
Auxiliary Space: O(n)
Approach 2 (Constant Space):
The idea is to compare elements of the original array sequence with its rotated versions. The rotated versions of the array are achieved using shifted index method where you compare elements at the original index with elements on the shifted index, without requiring any extra space.
Illustration:
Given array arr[]={2, 4, 6, 8}. count=0. We will use modulo operation to compare the two different indexes of the same array.
- In first iteration : {2, 4, 6, 8} & {2 ,4, 6, 8} , count=1
- In second iteration : {2, 4, 6, 8} & {2 ,4, 6, 8} , count=2
- In third iteration : {2, 4, 6, 8} & {2 ,4, 6, 8} , count=3
- In fourth iteration : {2, 4, 6, 8} & {2 ,4, 6, 8} , count=4
- count = size of original array, hence output is 4
Follow the steps below for the above idea:
We will perform rotation on the array and for each rotation, we will check if the value of the array at any index i , matches with the value of index j. Where j determines the rotation and i as the actual index for which the comparison has to be made.
- j = 1,2,3 … , n-1 & i= 0, 1, 2 , … ,n-1, n is the size of our array.
- If arr[i] not equal to arr[(i+j)%n] we will increase our counter value
- Else if the values don’t match, we don’t have to perform any operation
- Inside the checking loop, we will also have to keep a check if the value of counter = size of the original array, as it is the maximum value that we can obtain. If the condition matches, we may return the value. This condition optimizes our code.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxHamming( int arr[], int n){
int hmmd;
for ( int j = 1; j < n; j++){
hmmd = 0;
for ( int i = 0 ; i < n; i++){
if (arr[i] != arr[(i + j) % n])
hmmd++;
}
if (hmmd == n)
return n;
}
return hmmd;
}
int main()
{
int arr[] = {2, 4, 6, 8};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << maxHamming(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int maxHamming( int arr[], int n){
int hmmd = 0 ;
for ( int j = 1 ; j < n; j++){
hmmd = 0 ;
for ( int i = 0 ; i < n; i++){
if (arr[i] != arr[(i + j) % n])
hmmd++;
}
if (hmmd == n)
return n;
}
return hmmd;
}
public static void main(String args[])
{
int arr[] = { 2 , 4 , 6 , 8 };
int n = arr.length;
System.out.println(maxHamming(arr, n));
}
}
|
Python3
def maxHamming(arr, n):
hmmd = 0
for j in range ( 1 ,n):
hmmd = 0
for i in range (n):
if (arr[i] ! = arr[(i + j) % n]):
hmmd + = 1
if (hmmd = = n):
return n
return hmmd
arr = [ 2 , 4 , 6 , 8 ]
n = len (arr)
print (maxHamming(arr, n))
|
C#
using System;
class GFG
{
static int maxHamming( int [] arr, int n)
{
int hmmd = 0;
for ( int j = 1; j < n; j++)
{
hmmd = 0;
for ( int i = 0; i < n; i++)
{
if (arr[i] != arr[(i + j) % n])
hmmd++;
}
if (hmmd == n)
return n;
}
return hmmd;
}
public static void Main()
{
int [] arr = { 2, 4, 6, 8 };
int n = arr.Length;
Console.Write(maxHamming(arr, n));
}
}
|
Javascript
<script>
function maxHamming(arr, n){
let hmmd;
for (let j = 1; j < n; j++){
hmmd = 0;
for (let i = 0 ; i < n; i++){
if (arr[i] != arr[(i + j) % n])
hmmd++;
}
if (hmmd == n)
return n;
}
return hmmd;
}
let arr = [2, 4, 6, 8];
let n = arr.length;
document.write(maxHamming(arr, n), "</br>" );
</script>
|
PHP
<?php
function maxHamming( $arr , $n ) {
$hmmd = 0;
for ( $j = 1; $j < $n ; $j ++) {
$temp_hmmd = 0;
for ( $i = 0; $i < $n ; $i ++) {
if ( $arr [ $i ] != $arr [( $i + $j ) % $n ]) {
$temp_hmmd ++;
}
}
if ( $temp_hmmd == $n ) {
return $n ;
}
if ( $temp_hmmd > $hmmd ) {
$hmmd = $temp_hmmd ;
}
}
return $hmmd ;
}
$arr = array (2, 4, 6, 8);
$n = count ( $arr );
echo maxHamming( $arr , $n );
?>
|
Time Complexity: O(n2), Where n is the size of the given array
Auxiliary Space: O(1)
Approach 3 (Using list comprehension) :
We can find the maximum hamming distance using a different approach by taking advantage of list comprehension in python. In this method, we divide the job into 3 separate functions.
- hamming_distance(x : list, y : list): This method returns the hamming distance for two lists passed as parameters. The idea is to count the positions at which elements are different at the same index in two lists x and y where x is the original array taken in input and y is one of it rotations.
- Initialize a variable count from 0.
- Run a loop from starting index 0 to last index (n-1) where n is the length of the list.
- For each iteration check if element of x and element at index i (0<=i<=n-1) is same or not. If they are the same, increment the counter.
- After the loop is completed, return the count(by definition this is the hamming distance for given arrays or strings)
- rotate_by_one(arr : list): This method rotates the array (passed in argument ) in anti-clockwise direction by 1 position. For e.g. if array [1,1,4,4] is passed, this method returns [1,4,4,5,1].
- The idea is to copy the 1st element of the array and save it in a variable (say x).
- Then iterate the array from 0 to n-2 and copy every i+1th value at the ith position. Now assign x to the last index.
- max_hamming_distance(arr: list): This method finds the maximum hamming distance for a given array and its rotations. Follow the below steps in this method.
- We copy this array in a new array (say a) and initialize a variable max.
- Now, after every n rotations, we get the original array. So we need to find the hamming distance for the original array with it’s n-1 rotations and store the current maximum in a variable(say max).
- Run loop for n-1 iterations. For each iteration.
Follow the steps below for the above idea:
- Get the next rotation of arr by calling the method ‘rotate_by_one’.
- Call method hamming distance() and pass an original array (a) and current rotation of an (arr) and store the current hamming distance returned in a variable (say curr_h_dist).
- Check if the value of curr_h_dist is greater than the value of max. If yes, assign the value of curr_h_dist to max_h.
- Repeat steps 1-3 till the loop terminates.
- Return maximum hamming distance (max_h)
Below is the implementation of the above idea:
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int hammingDistance(vector< int > x, vector< int > y) {
int count = 0;
for ( int i = 0; i < x.size(); i++) {
if (x[i] != y[i]) {
count++;
}
}
return count;
}
void rotateByOne(vector< int >& arr) {
int x = arr[0];
for ( int i = 0; i < arr.size() - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.size() - 1] = x;
}
int max_hamming_distance(vector< int > arr) {
int maxH = -9999999;
int n = arr.size();
vector< int > a(arr);
for ( int i = 1; i < n; i++) {
rotateByOne(arr);
cout << "Array after " << i << " rotation : " ;
for ( int j = 0; j < n; j++) {
cout << arr[j] << " " ;
}
cout << endl;
int currHDist = hammingDistance(a, arr);
cout << "Hamming Distance with " << i << " rotations: " << currHDist << endl;
if (currHDist > maxH) {
maxH = currHDist;
}
cout << endl;
}
return maxH;
}
int main() {
vector< int > arr = {3, 0, 6, 4, 3};
cout << "Original Array : " ;
for ( int i = 0; i < arr.size(); i++) {
cout << arr[i] << " " ;
}
cout << endl;
cout << "Maximum Hamming Distance: " << max_hamming_distance(arr) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int hammingDistance( int [] x, int [] y)
{
int count = 0 ;
for ( int i = 0 ; i < x.length; i++) {
if (x[i] != y[i]) {
count++;
}
}
return count;
}
public static void rotateByOne( int [] arr)
{
int x = arr[ 0 ];
for ( int i = 0 ; i < arr.length - 1 ; i++) {
arr[i] = arr[i + 1 ];
}
arr[arr.length - 1 ] = x;
}
public static int max_hamming_distance( int [] arr)
{
int maxH = Integer.MIN_VALUE;
int n = arr.length;
int [] a = Arrays.copyOf(arr, arr.length);
for ( int i = 1 ; i < n; i++) {
rotateByOne(arr);
System.out.println( "Array after " + i
+ " rotation : "
+ Arrays.toString(arr));
int currHDist = hammingDistance(a, arr);
System.out.println( "Hamming Distance with " + i
+ " rotations: "
+ currHDist);
if (currHDist > maxH) {
maxH = currHDist;
}
System.out.println();
}
return maxH;
}
public static void main(String[] args)
{
int [] arr = { 3 , 0 , 6 , 4 , 3 };
long start = System.currentTimeMillis();
System.out.println();
System.out.println( "Original Array : "
+ Arrays.toString(arr));
System.out.println();
System.out.println( "Maximum Hamming Distance: "
+ max_hamming_distance(arr));
long end = System.currentTimeMillis();
System.out.println( "Execution Time = "
+ (end - start));
}
}
|
Python3
import time
def hamming_distance(x: list , y: list ):
count = 0
for i in range ( len (x)):
if (x[i] ! = y[i]):
count + = 1
return count
def rotate_by_one(arr: list ):
x = arr[ 0 ]
for i in range ( 0 , len (arr) - 1 ):
arr[i] = arr[i + 1 ]
arr[ len (arr) - 1 ] = x
def max_hamming_distance(arr: list ):
max_h = - 10000000000
n = len (arr)
a = []
for i in range (n):
a.append(arr[i])
for i in range ( 1 , n):
rotate_by_one(arr)
print ( "Array after %d rotation : " % (i), arr)
curr_h_dist = hamming_distance(a, arr)
print ( "Hamming Distance with %d rotations: %d" %
(i, curr_h_dist))
if curr_h_dist > max_h:
max_h = curr_h_dist
print ( '\n' )
return max_h
if __name__ = = '__main__' :
arr = [ 3 , 0 , 6 , 4 , 3 ]
start = time.time()
print ( '\n' )
print ( "Original Array : " , arr)
print ( '\n' )
print ( "Maximum Hamming Distance: " , max_hamming_distance(arr))
end = time.time()
print (f "Execution Time = {end - start}" )
|
Javascript
function hammingDistance(x, y) {
let count = 0;
for (let i = 0; i < x.length; i++) {
if (x[i] !== y[i]) {
count++;
}
}
return count;
}
function rotateByOne(arr) {
const x = arr[0];
for (let i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = x;
}
function maxHammingDistance(arr) {
let maxH = -Infinity;
const n = arr.length;
const a = [...arr];
for (let i = 1; i < n; i++) {
rotateByOne(arr);
console.log(`Array after ${i} rotation: ${arr.join( ' ' )}`);
const currHDist = hammingDistance(a, arr);
console.log(`Hamming Distance with ${i} rotations: ${currHDist}`);
if (currHDist > maxH) {
maxH = currHDist;
}
console.log( '' );
}
return maxH;
}
const arr = [3, 0, 6, 4, 3];
console.log(`Original Array: ${arr.join( ' ' )}`);
console.log(`Maximum Hamming Distance: ${maxHammingDistance(arr)}`);
|
C#
using System;
using System.Linq;
public class GFG {
public static int HammingDistance( int [] x, int [] y)
{
int count = 0;
for ( int i = 0; i < x.Length; i++) {
if (x[i] != y[i]) {
count++;
}
}
return count;
}
public static void RotateByOne( int [] arr)
{
int x = arr[0];
for ( int i = 0; i < arr.Length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.Length - 1] = x;
}
public static int MaxHammingDistance( int [] arr)
{
int maxH = int .MinValue;
int n = arr.Length;
int [] a = arr.ToArray();
for ( int i = 1; i < n; i++) {
RotateByOne(arr);
Console.WriteLine(
"Array after " + i + " rotation : ["
+ string .Join( ", " , arr) + "]" );
int currHDist = HammingDistance(a, arr);
Console.WriteLine( "Hamming Distance with " + i
+ " rotations: " + currHDist);
if (currHDist > maxH) {
maxH = currHDist;
}
Console.WriteLine();
}
return maxH;
}
static public void Main()
{
int [] arr = { 3, 0, 6, 4, 3 };
var start = DateTime.Now;
Console.WriteLine();
Console.WriteLine( "Original Array : ["
+ string .Join( ", " , arr) + "]" );
Console.WriteLine();
Console.WriteLine( "Maximum Hamming Distance: "
+ MaxHammingDistance(arr));
var end = DateTime.Now;
Console.WriteLine( "Execution Time = "
+ (end - start));
}
}
|
Output
Original Array : [3, 0, 6, 4, 3]
Array after 1 rotation : [0, 6, 4, 3, 3]
Hamming Distance with 1 rotations: 4
Array after 2 rotation : [6, 4, 3, 3, 0]
Hamming Distance with 2 rotations: 5
Array after 3 rotation : [4, 3, 3, 0, 6]
Hamming Distance with 3 rotations: 5
Array after 4 rotation : [3, 3, 0, 6, 4]
Hamming Distance with 4 rotations: 4
Maximum Hamming Distance: 5
Execution Time = 6.985664367675781e-05
Last Updated :
17 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...