Given an integer K such that there is a set of all possible perfect squares, each of length K. From this set of perfect squares, form a set of the longest possible length having those numbers which are anagram to each other. The task is to print the largest element present in the generated set of anagrams.
Note: If there is more than one set of maximum length, then print the largest number among them.
The anagram of a string is another string that contains the same characters, only the order of characters are different.
Examples:
Input: K = 2
Output: 81
Explanation:
All possible squares of length K = 2 are {16, 25, 36, 49, 64, 81}.
The possible anagram sets are [16], [25], [36], [49], [64], [81].
Therefore, each set is of the same size i.e., 1.
In this case, print the set containing the largest element, which is 81.
Input: K = 5
Output: 96100
Naive Approach: The simplest approach is to store all possible K length perfect squares and form a valid anagram sets using recursion. Then, find the maximum element present in the set of longest length.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The idea is based on the observation that on sorting the digits of the perfect squares, the sequence of anagram numbers becomes equal. Below are the steps:
- Initialise a Map to store all the anagram numbers corresponding to the numbers whose digit are arranged in sorted order.
- Generate all the perfect squares of length K.
- For each perfect square generated, insert the number in the Map corresponding to the number whose digit is arranged in ascending order.
- Traverse the Map and print the largest number from the set of maximum length.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void printResult(
map<string, set< long long int > > m)
{
auto max_itr = m.begin();
long long maxi = -1;
for ( auto itr = m.begin();
itr != m.end(); ++itr) {
long long int siz1
= (itr->second).size();
if (maxi < siz1) {
maxi = siz1;
max_itr = itr;
}
else if (maxi == siz1) {
if ((*(max_itr->second).rbegin())
< *(itr->second.rbegin())) {
maxi = siz1;
max_itr = itr;
}
}
}
long long int result
= *(max_itr->second).rbegin();
cout << result << endl;
}
void anagramicSquares( long long int k)
{
map<string, set< long long int > > m;
long long int end;
if (k % 2 == 0)
end = k / 2;
else
end = ((k + 1) / 2);
long long int start = pow (10, end - 1);
end = pow (10, end);
for ( long long int i = start;
i <= end; i++) {
long long int x = i * i;
ostringstream str1;
str1 << x;
string str = str1.str();
if (str.length() == k) {
sort(str.begin(), str.end());
m[str].insert(x);
}
}
printResult(m);
}
int main()
{
long long int K = 2;
anagramicSquares(K);
return 0;
}
|
Java
import java.util.*;
public class AnagramicSquares {
public static void
printResult(Map<String, Set<Long> > m)
{
Map.Entry<String, Set<Long> > maxItr
= m.entrySet().iterator().next();
long maxi = - 1 ;
for (Map.Entry<String, Set<Long> > entry :
m.entrySet()) {
long siz1 = entry.getValue().size();
if (maxi < siz1) {
maxi = siz1;
maxItr = entry;
}
else if (maxi == siz1) {
if (maxItr.getValue()
.stream()
.mapToLong(Long::longValue)
.max()
.getAsLong()
< entry.getValue()
.stream()
.mapToLong(Long::longValue)
.max()
.getAsLong()) {
maxi = siz1;
maxItr = entry;
}
}
}
long result = maxItr.getValue()
.stream()
.mapToLong(Long::longValue)
.max()
.getAsLong();
System.out.println(result);
}
public static void anagramicSquares( long k)
{
Map<String, Set<Long> > m = new HashMap<>();
long end;
if (k % 2 == 0 )
end = k / 2 ;
else
end = ((k + 1 ) / 2 );
long start = ( long )Math.pow( 10 , end - 1 );
end = ( long )Math.pow( 10 , end);
for ( long i = start; i <= end; i++) {
long x = i * i;
String str = Long.toString(x);
if (str.length() == k) {
char [] tempArr = str.toCharArray();
Arrays.sort(tempArr);
str = new String(tempArr);
if (!m.containsKey(str))
m.put(str, new HashSet<>());
m.get(str).add(x);
}
}
printResult(m);
}
public static void main(String[] args)
{
long K = 2 ;
anagramicSquares(K);
}
}
|
Python3
from typing import Dict , Set
import sys
def print_result(m: Dict [ str , Set [ int ]]) - > None :
max_itr = next ( iter (m.items()))
maxi = - 1
for itr in m.items():
siz1 = len (itr[ 1 ])
if maxi < siz1:
maxi = siz1
max_itr = itr
elif maxi = = siz1:
if max (max_itr[ 1 ]) < max (itr[ 1 ]):
maxi = siz1
max_itr = itr
result = max (max_itr[ 1 ])
print (result)
def anagramic_squares(k: int ) - > None :
m = {}
end = k / / 2 if k % 2 = = 0 else (k + 1 ) / / 2
start = 10 * * (end - 1 )
end = 10 * * end
for i in range (start, end):
x = i * i
str1 = str (x)
if len (str1) = = k:
str_sorted = "".join( sorted (str1))
m.setdefault(str_sorted, set ()).add(x)
print_result(m)
if __name__ = = "__main__" :
K = 2
anagramic_squares(K)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class AnagramicSquare
{
public static void PrintResult(Dictionary< string , HashSet< long >> m)
{
var maxItr = m.First();
long maxi = -1;
foreach ( var entry in m) {
long siz1 = entry.Value.Count;
if (maxi < siz1)
{
maxi = siz1;
maxItr = entry;
}
else if (maxi == siz1)
{
if (maxItr.Value.Max() < entry.Value.Max()) {
maxi = siz1;
maxItr = entry;
}
}
}
long result = maxItr.Value.Max();
Console.WriteLine(result);
}
public static void AnagramicSquares( long k)
{
Dictionary< string , HashSet< long >> m = new Dictionary< string , HashSet< long >>();
long end;
if (k % 2 == 0)
end = k / 2;
else
end = ((k + 1) / 2);
long start = ( long )Math.Pow(10, end - 1);
end = ( long )Math.Pow(10, end);
for ( long i = start; i <= end; i++) {
long x = i * i;
string str = x.ToString();
if (str.Length == k) {
char [] tempArr = str.ToCharArray();
Array.Sort(tempArr);
str = new string (tempArr);
if (!m.ContainsKey(str))
m.Add(str, new HashSet< long >());
m[str].Add(x);
}
}
PrintResult(m);
}
public static void Main( string [] args) {
long K = 2;
AnagramicSquares(K);
}
}
|
Javascript
function anagramicSquares(k) {
let m = new Map();
let end;
if (k % 2 === 0) {
end = k / 2;
} else {
end = (k + 1) / 2;
}
let start = Math.pow(10, end - 1);
end = Math.pow(10, end);
for (let i = start; i <= end; i++) {
let x = i * i;
let str = x.toString();
if (str.length === k) {
let tempArr = str.split( '' ).sort();
str = tempArr.join( '' );
if (!m.has(str)) {
m.set(str, new Set());
}
m.get(str).add(x);
}
}
printResult(m);
}
function printResult(m) {
let maxItr = Array.from(m.entries())[0];
let maxi = -1;
for (let [key, value] of m.entries()) {
let siz1 = value.size;
if (maxi < siz1) {
maxi = siz1;
maxItr = [key, value];
}
else if (maxi === siz1) {
let maxValue = Array.from(value).reduce((a, b) => Math.max(a, b));
let maxKey = Array.from(maxItr[1]).reduce((a, b) => Math.max(a, b));
if (maxValue > maxKey) {
maxi = siz1;
maxItr = [key, value];
}
}
}
let result = Array.from(maxItr[1]).reduce((a, b) => Math.max(a, b));
console.log(result);
}
let K = 2;
anagramicSquares(K);
|
Time Complexity: O(N)
Auxiliary Space: O(N)