Minimize Hamming Distance Problem

Ninja has strategically formed a team to combat enemies in his city. Each ninja in the team has a specific range of attack, and the team has successfully acquired the attack range information of their enemies. To optimize the attack strategy, ninja allows swaps between team members to minimize the Hamming distance, which is the count of differing positions between elements of the two arrays.

Input:

Given two arrays 'ninja' and 'enemies', both of the same length, and an 'allowedSwaps' array where each element [ai, bi] indicates the indices in the 'ninja' array which can be swapped.

Output:

Return the minimum Hamming distance between 'ninja' and 'enemies' after performing any number of such allowed swaps.

Example:

Input:
ninja = [1, 2, 3, 4] enemies = [2, 1, 4, 5] allowedSwaps = [[0, 1], [2, 3]]
Output:
1
Explanation:

By swapping indices 0 and 1, and 2 and 3, the ninja array becomes [2, 1, 4, 3], minimizing the Hamming distance to 1.

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 10^3
  • 1 ≤ ninja[i], enemies[i] < 10^5
  • 0 ≤ allowedSwaps.length ≤ 10^5

Note: Implement the function as specified. Do not handle output or input formatting.

AnswerBot
4mo

Minimize Hamming distance between two arrays by swapping elements at allowed indices.

  • Iterate through allowed swaps and swap elements in ninja array accordingly.

  • Calculate Hamming distance between ninja...read more

Help your peers!
Select
Add answer anonymously...

Cognizant Software Developer interview questions & answers

A Software Developer was asked 2w agoQ. What do you know about software development?
A Software Developer was asked 1mo agoQ. Can you explain memory leaks?
A Software Developer was asked 2mo agoQ. What is the procedure for configuring Snowpipe?

Popular interview questions of Software Developer

A Software Developer was asked 2w agoQ1. What do you know about software development?
A Software Developer was asked 1mo agoQ2. Can you explain memory leaks?
A Software Developer was asked 2mo agoQ3. What is the procedure for configuring Snowpipe?
Cognizant Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits