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 given input.
Input: arr = [1, 4, 1]
Explanation: Maximum hamming distance = 2, this hamming distance with 4 1 1 or 1 1 4
Input: arr = [2, 4, 8, 0]
Explanation: Maximum hamming distance = 4, this hamming distance with 4 8 0 2. All the places can be occupied by another digit. Other solutions can be 8 0 2 4, 4 0 2 8 etc.
Approach: This problem can be solved efficiently by using the Hashmap. Follow the steps given below to solve the problem
- Iterate through the array arr and store the values of the array in a HashMap <key, value>. Value can be List<> or string depending on interest.
- Add the value in hashmap, hashMap.add(arrvalue, list).
- Check this condition:
- When the hashMap.contains(arrValue) then hashmap.get(arrayValue).append(index).
- Check the size of the hashmap, if size == 1 then
- max hamming distance = 0. Because all values are the same.
- Run the for each loop, for each key if the list size = 1 then
- max hamming distance = n. Because all values are diff.
- Create an array of size – 1 of the given array for storing the similar occurrences that can happen.
- After storing all the indexes of array store the values in hashMap.
- For each difference found a += 1. This difference says the number of rotations it would take to have the same value in the same position.
- Find the least value in the array and get the index => min same values => max hamming distance.
Below is the implementation of the above approach:
Time complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.