The Wayback Machine - https://web.archive.org/web/20240817090033/https://www.geeksforgeeks.org/find-a-rotation-with-maximum-hamming-distance/
Open In App

Find a rotation with maximum hamming distance

Last Updated : 17 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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++




// C++ program to Find another array such that the hamming
// distance from the original array is maximum
#include <bits/stdc++.h>
using namespace std;
 
// Return the maximum hamming distance of a rotation
int maxHamming(int arr[], int n)
{
    // arr[] to brr[] two times so that
    // we can traverse through all rotations.
    int brr[2 * n + 1];
    for (int i = 0; i < n; i++) {
        brr[i] = arr[i];
        brr[n + i] = arr[i];
    }
 
    // We know hamming distance with 0 rotation would be 0.
    int maxHam = 0;
 
    // We try other rotations one by one and compute
    // Hamming distance of every rotation
    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++;
 
        // We can never get more than n.
        if (currHam == n)
            return n;
 
        maxHam = max(maxHam, currHam);
    }
 
    return maxHam;
}
 
// Driver program
int main()
{
    int arr[] = { 2, 4, 6, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxHamming(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to Find another array such that the hamming
// distance from the original array is maximum
#include <stdio.h>
 
// Find maximum between two numbers.
int max(int num1, int num2)
{
    return (num1 > num2) ? num1 : num2;
}
 
// Return the maximum hamming distance of a rotation
int maxHamming(int arr[], int n)
{
    // arr[] to brr[] two times so that
    // we can traverse through all rotations.
    int brr[2 * n + 1];
    for (int i = 0; i < n; i++) {
        brr[i] = arr[i];
        brr[n + i] = arr[i];
    }
 
    // We know hamming distance with 0 rotation would be 0.
    int maxHam = 0;
 
    // We try other rotations one by one and compute
    // Hamming distance of every rotation
    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++;
 
        // We can never get more than n.
        if (currHam == n)
            return n;
 
        maxHam = max(maxHam, currHam);
    }
 
    return maxHam;
}
 
// Driver program
int main()
{
    int arr[] = { 2, 4, 6, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", maxHamming(arr, n));
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to Find another array
// such that the hamming distance
// from the original array is maximum
 
import java.io.*;
 
class GFG {
    // Return the maximum hamming
    // distance of a rotation
    static int maxHamming(int arr[], int n)
    {
        // arr[] to brr[] two times so that
        // we can traverse through all rotations.
        int brr[] = new int[2 * n + 1];
        for (int i = 0; i < n; i++) {
            brr[i] = arr[i];
            brr[n + i] = arr[i];
        }
 
        // We know hamming distance with
        // 0 rotation would be 0.
        int maxHam = 0;
 
        // We try other rotations one by one
        // and compute Hamming distance
        // of every rotation
        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++;
 
            // We can never get more than n.
            if (currHam == n)
                return n;
 
            maxHam = Math.max(maxHam, currHam);
        }
 
        return maxHam;
    }
 
    // driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 4, 6, 8 };
        int n = arr.length;
        System.out.print(maxHamming(arr, n));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python3 code to Find another array
# such that the hamming distance
# from the original array is maximum
 
# Return the maximum hamming
# distance of a rotation
def maxHamming( arr , n ):
 
    # arr[] to brr[] two times so
    # that we can traverse through
    # all rotations.
    brr = [0] * (2 * n + 1)
    for i in range(n):
        brr[i] = arr[i]
    for i in range(n):
        brr[n+i] = arr[i]
     
    # We know hamming distance
    # with 0 rotation would be 0.
    maxHam = 0
     
    # We try other rotations one by
    # one and compute Hamming
    # distance of every rotation
    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
         
        # We can never get more than n.
        if currHam == n:
            return n
         
        maxHam = max(maxHam, currHam)
     
    return maxHam
 
# driver program
arr = [2, 4, 6, 8]
n = len(arr)
print(maxHamming(arr, n))
 
# This code is contributed by "Sharad_Bhardwaj".


C#




// C# program to Find another array
// such that the hamming distance
// from the original array is maximum
using System;
 
class GFG {
     
    // Return the maximum hamming
    // distance of a rotation
    static int maxHamming(int []arr, int n)
    {
         
        // arr[] to brr[] two times so that
        // we can traverse through all rotations.
        int []brr=new int[2 * n + 1];
         
        for (int i = 0; i < n; i++){
            brr[i] = arr[i];
            brr[n+i] = arr[i];
        }
     
        // We know hamming distance with
        // 0 rotation would be 0.
        int maxHam = 0;
     
        // We try other rotations one by one
        // and compute Hamming distance
        // of every rotation
        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++;
     
            // We can never get more than n.
            if (currHam == n)
                return n;
     
            maxHam = Math.Max(maxHam, currHam);
        }
     
        return maxHam;
    }
     
    // driver code
    public static void Main ()
    {
        int []arr = {2, 4, 6, 8};
        int n = arr.Length;
        Console.Write(maxHamming(arr, n));
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP program to Find another array
// such that the hamming distance
// from the original array is maximum
 
// Return the maximum hamming
// distance of a rotation
function maxHamming($arr, $n)
{
     
    // arr[] to brr[] two times so that
    // we can traverse through all rotations.
    $brr = array();
    for ($i = 0; $i < $n; $i++)
        $brr[$i] = $arr[$i];
    for ($i = 0; $i < $n; $i++)
        $brr[$n+$i] = $arr[$i];
 
    // We know hamming distance
    // with 0 rotation would be 0.
    $maxHam = 0;
 
    // We try other rotations one
    // by one and compute Hamming
    // distance of every rotation
    for ($i = 1; $i < $n; $i++)
    {
        $currHam = 0;
        for ( $j = $i, $k = 0; $j < ($i + $n);
                                  $j++, $k++)
            if ($brr[$j] != $arr[$k])
                $currHam++;
 
        // We can never get more than n.
        if ($currHam == $n)
            return $n;
 
        $maxHam = max($maxHam, $currHam);
    }
 
    return $maxHam;
}
 
    // Driver Code
    $arr = array(2, 4, 6, 80);
    $n = count($arr);
    echo maxHamming($arr, $n);
 
// This code is contributed by anuj_67.
?>


Javascript




<script>
// JavaScript program to Find another array
// such that the hamming distance
// from the original array is maximum
 
// Return the maximum hamming distance of a rotation
function maxHamming(arr, n)
{
    // arr[] to brr[] two times so that
    // we can traverse through all rotations.
    let brr = new Array(2 *n + 1);
    for (let i = 0; i < n; i++){
        brr[i] = arr[i];
        brr[n+i] = arr[i];
        }
 
    // We know hamming distance with 0 rotation
    // would be 0.
    let maxHam = 0;
 
    // We try other rotations one by one and compute
    // Hamming distance of every rotation
    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++;
 
        // We can never get more than n.
        if (currHam == n)
            return n;
 
        maxHam = max(maxHam, currHam);
    }
 
    return maxHam;
}
 
// driver program
    let arr = [2, 4, 6, 8];
    let n = arr.length;
    document.write(maxHamming(arr, n));
 
 
 
 
// This code is contributed by Surbhi Tyagi.
</script>


Output

4

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++




// C++ program to Find another array
// such that the hamming distance
// from the original array is maximum
 
// requires O(n*n) time and O(1) extra space;
#include <bits/stdc++.h>
using namespace std;
 
// Return the maximum hamming distance of a rotation
int maxHamming(int arr[], int n){
    int hmmd;
      // outer loop for how much rotation
    for(int j = 1; j < n; j++){
        hmmd = 0;
          //inner loop to compare elements with elements on shifted index
        for(int i = 0 ; i < n; i++){
            if(arr[i] != arr[(i + j) % n])
                hmmd++;
        }
          //max possible hamming distance is n, no need to check further
        if(hmmd == n)
            return n;
    }
    return hmmd;
}
 
// driver program
int main()
{
    int arr[] = {2, 4, 6, 8};   
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << maxHamming(arr, n);   
    return 0;
}
 
// This method is contributed by nehalrandive


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG
{
   
// Java program to Find another array
// such that the hamming distance
// from the original array is maximum
 
// requires O(n*n) time and O(1) extra space;
 
// Return the maximum hamming distance of a rotation
static int maxHamming(int arr[], int n){
         
    int hmmd = 0;
         
    // outer loop for how much rotation
    for(int j = 1; j < n; j++){
         
        hmmd = 0;
       
        // inner loop to compare elements with elements on shifted index
        for(int i = 0 ; i < n; i++){
            if(arr[i] != arr[(i + j) % n])
                hmmd++;
        }
       
        // max possible hamming distance is n, no need to check further
        if(hmmd == n)
            return n;
    }
    return hmmd;
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = {2, 4, 6, 8};   
    int n = arr.length;
    System.out.println(maxHamming(arr, n));  
}
}
 
// This code is contributed by shinjanpatra


Python3




# Python3 program to Find another array
# such that the hamming distance
# from the original array is maximum
 
# requires O(n*n) time and O(1) extra space;
 
# Return the maximum hamming distance of a rotation
def maxHamming(arr, n):
     
    # outer loop for how much rotation
    hmmd = 0
 
    for j in range(1,n):
        hmmd = 0
        #inner loop to compare elements with elements on shifted index
        for i in range(n):
            if(arr[i] != arr[(i + j) % n]):
                hmmd += 1
         
            #max possible hamming distance is n, no need to check further
        if(hmmd == n):
            return n
    return hmmd
 
# driver program
arr = [2, 4, 6, 8]
n = len(arr)
print(maxHamming(arr, n))   
 
 
# This code is contributed by shinjanpatra


C#




// C# program to Find another array
// such that the hamming distance
// from the original array is maximum
 
// requires O(n*n) time and O(1) extra space;using System;
using System;
class GFG
{
 
  // Return the maximum hamming distance of a rotation
  static int maxHamming(int[] arr, int n)
  {
 
    int hmmd = 0;
 
    // outer loop for how much rotation
    for (int j = 1; j < n; j++)
    {
 
      hmmd = 0;
 
      // inner loop to compare elements with elements on shifted index
      for (int i = 0; i < n; i++)
      {
        if (arr[i] != arr[(i + j) % n])
          hmmd++;
      }
 
      // max possible hamming distance is n, no need to check further
      if (hmmd == n)
        return n;
    }
    return hmmd;
  }
 
  // Driver code
  public static void Main()
  {
    int[] arr = { 2, 4, 6, 8 };
    int n = arr.Length;
    Console.Write(maxHamming(arr, n));
  }
}
 
// This code is contributed by saurabh_jaiswal.


Javascript




<script>
 
// JavaScript program to Find another array
// such that the hamming distance
// from the original array is maximum
 
// requires O(n*n) time and O(1) extra space;
 
// Return the maximum hamming distance of a rotation
function maxHamming(arr, n){
    let hmmd;
      // outer loop for how much rotation
    for(let j = 1; j < n; j++){
        hmmd = 0;
          //inner loop to compare elements with elements on shifted index
        for(let i = 0 ; i < n; i++){
            if(arr[i] != arr[(i + j) % n])
                hmmd++;
        }
          //max possible hamming distance is n, no need to check further
        if(hmmd == n)
            return n;
    }
    return hmmd;
}
 
// driver program
 
let arr = [2, 4, 6, 8];
let n = arr.length;
document.write(maxHamming(arr, n),"</br>");   
 
 
// This method is contributed by shinjanpatra
 
</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);
 
?>


Output

4

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:

  1. Get the next rotation of arr by calling the method ‘rotate_by_one’.
  2. 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).
  3. 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.
  4. Repeat steps 1-3 till the loop terminates.
  5. Return maximum hamming distance (max_h)

Below is the implementation of the above idea:

C++




#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
// Function to find the hamming distance
// for two vectors
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;
}
 
// Function to rotate the given vector
// in anti-clockwise direction by 1
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;
}
 
// Function maxHammingDistance to find
// the maximum hamming distance for given vector
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




// Java code to find maximum of an array with it's rotations
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find the hamming distance
    // for two lists/strings
    public static int hammingDistance(int[] x, int[] y)
    {
        // Initialize count
        int count = 0;
 
        // Run loop for size of x(or y)
        // as both as same length
        for (int i = 0; i < x.length; i++) {
            // Check if corresponding elements
            // at same index are not equal
            if (x[i] != y[i]) {
                // Increment the count every
                // time above condition satisfies
                count++;
            }
        }
        // Return the hamming distance
        // for given pair of lists or strings
        return count;
    }
 
    // Function to rotate the given array
    // in anti-clockwise direction by 1
    public static void rotateByOne(int[] arr)
    {
        // Store 1st element in a variable
        int x = arr[0];
 
        // Update each ith element (0<=i<=n-2)
        // with it's next value
        for (int i = 0; i < arr.length - 1; i++) {
            arr[i] = arr[i + 1];
        }
 
        // Assign 1st element to the last index
        arr[arr.length - 1] = x;
    }
 
    // Function maxHammingDistance to find
    // the maximum hamming distance for given array
    public static int max_hamming_distance(int[] arr)
    {
        // Initialize a variable to store
        // maximum hamming distance
        int maxH = Integer.MIN_VALUE;
 
        // Store size of the given array
        // in a variable n
        int n = arr.length;
 
        // Initialize a new array
        int[] a = Arrays.copyOf(arr, arr.length);
 
        // Run loop for i=0 to i=n-1 for n-1 rotations
        for (int i = 1; i < n; i++) {
            // Find the next rotation
            rotateByOne(arr);
            System.out.println("Array after " + i
                               + " rotation : "
                               + Arrays.toString(arr));
 
            // Store hamming distance of current
            // rotation with original array
            int currHDist = hammingDistance(a, arr);
            System.out.println("Hamming Distance with " + i
                               + " rotations: "
                               + currHDist);
 
            // Check if current hamming distance
            // is greater than max hamming distance
            if (currHDist > maxH) {
                // If yes, assign value of current
                // hamming distance to max hamming distance
                maxH = currHDist;
            }
            System.out.println();
        }
        // Return maximum hamming distance
        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));
    }
}
 
// This code is contributed by lokeshmvs21.


Python3




# Python code to find maximum
# of an array with it's rotations
import time
 
# Function hamming distance to find
# the hamming distance for two lists/strings
def hamming_distance(x: list, y: list):
   
    # Initialize count
    count = 0
     
    # Run loop for size of x(or y)
    # as both as same length
    for i in range(len(x)):
       
        # Check if corresponding elements
        # at same index are not equal
        if(x[i] != y[i]):
           
            # Increment the count every
            # time above condition satisfies
            count += 1
             
    # Return the hamming distance
    # for given pair of lists or strings
    return count
 
 
# Function to rotate the given array
# in anti-clockwise direction by 1
def rotate_by_one(arr: list):
   
    # Store 1st element in a variable
    x = arr[0]
     
    # Update each ith element (0<=i<=n-2)
    # with it's next value
    for i in range(0, len(arr)-1):
        arr[i] = arr[i+1]
       
    # Assign 1st element to the last index
    arr[len(arr)-1] = x
 
 
# Function max_hamming_distance to find
# the maximum hamming distance for given array
def max_hamming_distance(arr: list):
   
    # Initialize a variable to store
    # maximum hamming distance
    max_h = -10000000000
     
    # Store size of the given array
    # in a variable n
    n = len(arr)
     
    # Initialize a new array
    a = []
     
    # Copy the original array in new array
    for i in range(n):
        a.append(arr[i])
         
    # Run loop for i=0 to i=n-1 for n-1 rotations
    for i in range(1, n):
       
        # Find the next rotation
        rotate_by_one(arr)
        print("Array after %d rotation : " % (i), arr)
         
        # Store hamming distance of current
        # rotation with original array
        curr_h_dist = hamming_distance(a, arr)
        print("Hamming Distance with %d rotations: %d" %
                                        (i, curr_h_dist))
         
        # Check if current hamming distance
        # is greater than max hamming distance
        if curr_h_dist > max_h:
           
            # If yes, assign value of current
            # hamming distance to max hamming distance
            max_h = curr_h_dist
             
        print('\n')
    # Return maximum hamming distance
    return max_h
 
 
# Driver code
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}")
# This code is contributed by Vivek_Kumar_Sinha


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#




// C# code to find maximum of an array with it's rotations
using System;
using System.Linq;
 
public class GFG {
 
  // Function to find the hamming distance
  // for two lists/strings
  public static int HammingDistance(int[] x, int[] y)
  {
    // Initialize count
    int count = 0;
 
    // Run loop for size of x(or y)
    // as both as same length
    for (int i = 0; i < x.Length; i++) {
      // Check if corresponding elements
      // at same index are not equal
      if (x[i] != y[i]) {
        // Increment the count every
        // time above condition satisfies
        count++;
      }
    }
    // Return the hamming distance
    // for given pair of lists or strings
    return count;
  }
 
  // Function to rotate the given array
  // in anti-clockwise direction by 1
  public static void RotateByOne(int[] arr)
  {
    // Store 1st element in a variable
    int x = arr[0];
 
    // Update each ith element (0<=i<=n-2)
    // with it's next value
    for (int i = 0; i < arr.Length - 1; i++) {
      arr[i] = arr[i + 1];
    }
 
    // Assign 1st element to the last index
    arr[arr.Length - 1] = x;
  }
 
  // Function maxHammingDistance to find
  // the maximum hamming distance for given array
  public static int MaxHammingDistance(int[] arr)
  {
    // Initialize a variable to store
    // maximum hamming distance
    int maxH = int.MinValue;
 
    // Store size of the given array
    // in a variable n
    int n = arr.Length;
 
    // Initialize a new array
    int[] a = arr.ToArray();
 
    // Run loop for i=0 to i=n-1 for n-1 rotations
    for (int i = 1; i < n; i++) {
      // Find the next rotation
      RotateByOne(arr);
      Console.WriteLine(
        "Array after " + i + " rotation : ["
        + string.Join(", ", arr) + "]");
 
      // Store hamming distance of current
      // rotation with original array
      int currHDist = HammingDistance(a, arr);
      Console.WriteLine("Hamming Distance with " + i
                        + " rotations: " + currHDist);
 
      // Check if current hamming distance
      // is greater than max hamming distance
      if (currHDist > maxH) {
        // If yes, assign value of current
        // hamming distance to max hamming distance
        maxH = currHDist;
      }
      Console.WriteLine();
    }
    // Return maximum hamming distance
    return maxH;
  }
 
  static public void Main()
  {
 
    // Code
    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));
  }
}
 
// This code is contributed by lokeshmvs21.


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


Similar Reads

Generate string with Hamming Distance as half of the hamming distance between strings A and B
Given two Binary string A and B of length N, the task is to find the Binary string whose Hamming Distance to strings A and B is half the Hamming Distance of A and B.Examples: Input: A = "1001010", B = "0101010" Output: 0001010 Explanation: The hamming distance of the string A and B is 2. The hamming distance of the output string to A is 1. The hamm
7 min read
Find a rotation with maximum hamming distance | Set 2
Given an integer array arr[]. Create a new array which is a rotation of given array and find the maximum Hamming distance between both the arrays. Hamming distance between two arrays or strings of equal length is the number of positions at which the corresponding character(elements) are different. Note: There can be more than one output for the giv
10 min read
Reduce Hamming distance by swapping two characters
Given two strings S and T. Find the positions of two letters to be swapped in S so that the hamming distance between strings S and T is as small as possible. Hamming Distance: Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters Examples: Input : S =
10 min read
Concepts of hamming distance
Hamming Distance Problem: In general, it is assumed that it is more likely to have fewer errors than more errors. This “worst-case” approach to coding is intuitively appealing within itself. Nevertheless, it is closely connected to a simple probabilistic model where errors are introduced into the message independently for each symbol and with a fix
2 min read
Minimize hamming distance in Binary String by setting only one K size substring bits
Given two binary strings S and T of length N and a positive integer K. Initially, all characters of T are '0'. The task is to find the minimum Hamming distance after choosing a substring of size K and making all elements of string T as '1' only once. Examples: Input: S = "101", K = 2Output: 1Explanation: Initially string T = "000", one possible way
7 min read
Hamming distance between two Integers
Given two integers, the task is to find the hamming distance between two integers. Hamming Distance between two integers is the number of bits that are different at the same position in both numbers. Examples: Input: n1 = 9, n2 = 14Output: 39 = 1001, 14 = 1110No. of Different bits = 3Input: n1 = 4, n2 = 8Output: 2Approach: Calculate the XOR of two
9 min read
Hamming Distance between two strings
You are given two strings of equal length, you have to find the Hamming Distance between these string. Where the Hamming distance between two strings of equal length is the number of positions at which the corresponding character is different. Examples: Input : str1[] = "geeksforgeeks", str2[] = "geeksandgeeks" Output : 3 Explanation : The correspo
4 min read
Lexicographically smallest string whose hamming distance from given string is exactly K
Given a lowercase string A of length N and an integer K, find the lexicographically smallest string B of the same length as A such that hamming distance between A and B is exactly K. Examples: Input : A = "pqrs", k = 1. Output : aqrs We can differ by at most one character. So we put 'a' in the beginning to make the result lexicographically smallest
8 min read
Python3 Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n)Right (Or clockwise) rotate the given string by d elements (where d &lt;= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation :
3 min read
Javascript Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n)Right (Or clockwise) rotate the given string by d elements (where d &lt;= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation :
3 min read
Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n) Right (Or clockwise) rotate the given string by d elements (where d &lt;= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "
15+ min read
Find K such that sum of hamming distances between K and each Array element is minimised
Given an array arr[] of N non-negative integers and an integer P (1 ≤ P ≤ 30), which denotes the upper limit of any number in the array to be (2P - 1). The task is to find a number such that the sum of Hamming distances between the number itself and all the numbers in the array is minimum. If there are multiple answers possible print any one of the
12 min read
Python3 Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0."0011": Count of 0
5 min read
Javascript Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0."0011": Count of 0
5 min read
Count paths with distance equal to Manhattan distance
Given two points (x1, y1) and (x2, y2) in 2-D coordinate system. The task is to count all the paths whose distance is equal to the Manhattan distance between both the given points.Examples: Input: x1 = 2, y1 = 3, x2 = 4, y2 = 5 Output: 6Input: x1 = 2, y1 = 6, x2 = 4, y2 = 9 Output: 10 Approach: The Manhattan distance between the points (x1, y1) and
7 min read
Distance of chord from center when distance between center and another equal length chord is given
Given two equal length chords of a circle and Distance between the centre and one chord. The task is here to find the distance between the centre and the other chord. Examples: Input: 48 Output: 48 Input: 82 Output: 82 Below is the implementation of the above approach:Approach: Let AB &amp; CD be the two equal chords of the circle having center at
3 min read
Minimal distance such that for every customer there is at least one vendor at given distance
Given N and M number of points on the straight line, denoting the positions of the customers and vendors respectively. Each vendor provides service to all customers, which are located at a distance that is no more than R from the vendor. The task is to find minimum R such that for each customer there is at least one vendor at the distance which is
7 min read
Maximise distance by rearranging all duplicates at same distance in given Array
Given an array arr[] of N integers. Arrange the array in a way such that the minimum distance among all pairs of same elements is maximum among all possible arrangements. The task is to find this maximum value. Examples: Input: arr[] = {1, 1, 2, 3}Output: 3Explanation: All possible arrangements are: {1, 1, 2, 3}, {1, 1, 3, 2}, {1, 2, 1, 3}, {1, 2,
6 min read
Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0."0011": Count of 0
15+ min read
Maximum product of first and last character of String after rotation
Given a string S of length N, the task is to find the maximum possible product of the first and the last character of the string if it is rotated any number of times toward left or right. Examples: Input: Str = "12345" Output: 20Explanation: If we rotate the string once in anticlockwise direction, then the string becomes 51234, and the product = 5*
4 min read
Find determinant of matrix generated by array rotation
Given an array of three elements. The task is to construct a matrix of order 3×3 by using all three rotations of the array as a row of the matrix and find the determinant of the resultant matrix. Examples: Input : arr[] = {1, 2, 3} Output : 18 Input : arr[] = {1, 1, 1} Output : 0 Approach: As per the problem statement, construct a 3*3 matrix using
4 min read
Python3 Program to Find Lexicographically minimum string rotation | Set 1
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples:  Input: GEEKSQUIZ Output: EEKSQUIZG Input: GFG Output: FGG Input: GEEKSFORGEEKS Output: EEKSFORGEEKSG Following is a simple solution. Let the given string be 'str' 1) Concatenat
2 min read
Javascript Program to Find Lexicographically minimum string rotation | Set 1
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples:  Input: GEEKSQUIZ Output: EEKSQUIZG Input: GFG Output: FGG Input: GEEKSFORGEEKS Output: EEKSFORGEEKSG Following is a simple solution. Let the given string be 'str' 1) Concatenat
2 min read
Find the Rotation Count in Rotated Sorted array
Given an array arr[] of size N having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}Output: 2Explanation: Initial array must
15+ min read
Find maximum and minimum distance between magnets
Given coordinates of two pivot points (x0, y0) &amp; (x1, y1) in coordinates plane. Along with each pivot, two different magnets are tied with the help of a string of length r1 and r2 respectively. Find the distance between both magnets when they repel each other and when they are attracting each other. Examples : Input : x1=0, y1=0, x2=5, y2=0, r1
6 min read
Find maximum distance between any city and station
Given the number of cities n numbered from 0 to n-1 and the cities in which stations are located, the task is to find the maximum distance between any city and its nearest station. Note that the cities with stations can be given in any order. Examples: Input: numOfCities = 6, stations = [1, 4] Output: 1 Input: numOfCities = 6, stations = [3] Output
7 min read
Find the maximum possible distance from origin using given points
Given N 2-Dimensional points. The task is to find the maximum possible distance from the origin using given points. Using the ith point (xi, yi) one can move from (a, b) to (a + xi, b + yi). Note: N lies between 1 to 1000 and each point can be used at most once.Examples: Input: arr[][] = {{1, 1}, {2, 2}, {3, 3}, {4, 4}} Output: 14.14 The farthest p
6 min read
Find Maximum Shortest Distance in Each Component of a Graph
Given an adjacency matrix graph[][] of a weighted graph consisting of N nodes and positive weights, the task for each connected component of the graph is to find the maximum among all possible shortest distances between every pair of nodes. Examples: Input: Output: 8 0 11 Explanation: There are three components in the graph namely a, b, c. In compo
15+ min read
Find Maximum number of intersecting points with at most K distance
Two players A and B are standing at starting point 0 of an infinite horizontal line. Player A is given an array with jumpA[] of size M and Player B is given an array with jumpB[] of size N. Both players can make jumps as: Player A can jump D distance in both directions (right or left), from its current point, such that D is present in jumpA[].Playe
8 min read
Find the maximum distance covered using n bikes
There are n bikes and each can cover 100 km when fully fueled. What is the maximum amount of distance you can go using n bikes? You may assume that all bikes are similar and a bike takes 1 litre to cover 1 km.You have n bikes and using one bike you can only cover 100 km. so if n bikes start from same point and run simultaneously you can go only 100
7 min read
three90RightbarBannerImg