Beautiful Pairs hackerrank Solution

Published on September 02, 2021
Last updated September 02, 2021

You are given two arrays, A and B, both containing N integers.

A pair of indices is beautiful if the element of array is equal to the
element of array . In other words, pair is beautiful if and only if . A set containing beautiful pairs is called a beautiful set.

A beautiful set is called pairwise disjoint if for every pair belonging to the set there is no repetition of either or values. For instance, if and
the beautiful set is not pairwise disjoint as there is a repetition of , that is .

Your task is to change exactly element in so that the size of the pairwise disjoint beautiful set is maximum.

Function Description

Complete the beautifulPairs function in the editor below. It should return an integer that represents the maximum number of pairwise disjoint beautiful pairs that can be formed.

beautifulPairs has the following parameters:

  • A: an array of integers
  • B: an array of integers

Input Format

The first line contains a single integer n, the number of elements in A and B.

The second line contains n space-separated integers A[i].

The third line contains n space-separated integers B[i].

Output Format

Determine and print the maximum possible number of pairwise disjoint beautiful pairs.

Note: You must first change 1 element in B, and your choice of element must be optimal.

Beautiful Pairs hackerrank Solution in java

// BeautifulPairs
import java.util.Scanner;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        int n = sc.nextInt();
        int[] count = new int[1002];
        int result = 0;
        for (int i = 0; i < n; i++)
        for (int i = 0; i < n; i++) {
            int temp = sc.nextInt();
            if (count[temp] > 0) {
        if (result == n)

Tags :