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:
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;
// Function to find the largest set of // perfect squares which are anagram // to each other 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();
// Check if size of maximum set
// is less than the current set
if (maxi < siz1) {
// Update maximum set
maxi = siz1;
max_itr = itr;
}
// If lengths are equal
else if (maxi == siz1) {
// Update maximum set to store
// the set with maximum element
if ((*(max_itr->second).rbegin())
< *(itr->second.rbegin())) {
maxi = siz1;
max_itr = itr;
}
}
}
// Stores the max element from the set
long long int result
= *(max_itr->second).rbegin();
// Print final Result
cout << result << endl;
} // Function to find the // perfect squares which are anagrams void anagramicSquares( long long int k)
{ // Stores the sequence
map<string, set< long long int > > m;
// Initialize start and end
// of perfect squares
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);
// Iterate from start to end
for ( long long int i = start;
i <= end; i++) {
long long int x = i * i;
// Converting int to string
ostringstream str1;
str1 << x;
string str = str1.str();
if (str.length() == k) {
// Sort string for storing
// number at exact map position
sort(str.begin(), str.end());
// Insert number at map
m[str].insert(x);
}
}
// Print result
printResult(m);
} // Driver Code int main()
{ // Given K
long long int K = 2;
// Function Call
anagramicSquares(K);
return 0;
} |
import java.util.*;
public class AnagramicSquares {
// Function to find the largest set of
// perfect squares which are anagram
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();
// Check if size of maximum set
// is less than the current set
if (maxi < siz1) {
// Update maximum set
maxi = siz1;
maxItr = entry;
}
// If lengths are equal
else if (maxi == siz1) {
// Update maximum set to store
// the set with maximum element
if (maxItr.getValue()
.stream()
.mapToLong(Long::longValue)
.max()
.getAsLong()
< entry.getValue()
.stream()
.mapToLong(Long::longValue)
.max()
.getAsLong()) {
maxi = siz1;
maxItr = entry;
}
}
}
// Stores the max element from the set
long result = maxItr.getValue()
.stream()
.mapToLong(Long::longValue)
.max()
.getAsLong();
// Print final Result
System.out.println(result);
}
// Function to find the
// perfect squares which are anagrams
public static void anagramicSquares( long k)
{
// Stores the sequence
Map<String, Set<Long> > m = new HashMap<>();
// Initialize start and end
// of perfect squares
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);
// Iterate form start to end
for ( long i = start; i <= end; i++) {
long x = i * i;
// Converting int to string
String str = Long.toString(x);
if (str.length() == k) {
// Sort string for storing
// number at exact map position
char [] tempArr = str.toCharArray();
Arrays.sort(tempArr);
str = new String(tempArr);
// Insert number at map
if (!m.containsKey(str))
m.put(str, new HashSet<>());
m.get(str).add(x);
}
}
// Print result
printResult(m);
}
// Driver Code
public static void main(String[] args)
{
// Given K
long K = 2 ;
// Function Call
anagramicSquares(K);
}
} // this code is contributed by devendra
|
# Python program for the above approach from typing import Dict , Set
import sys
# Function to find the largest set of # perfect squares which are anagram # to each other 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 ])
# Check if size of maximum set
# is less than the current set
if maxi < siz1:
# Update maximum set
maxi = siz1
max_itr = itr
# If lengths are equal
elif maxi = = siz1:
# Update maximum set to store
# the set with maximum element
if max (max_itr[ 1 ]) < max (itr[ 1 ]):
maxi = siz1
max_itr = itr
result = max (max_itr[ 1 ])
# Print final Result
print (result)
# Function to find the # perfect squares which are anagrams def anagramic_squares(k: int ) - > None :
# Stores the sequence
m = {}
end = k / / 2 if k % 2 = = 0 else (k + 1 ) / / 2
start = 10 * * (end - 1 )
end = 10 * * end
# Iterate from start to end
for i in range (start, end):
x = i * i
# Converting int to string
str1 = str (x)
if len (str1) = = k:
# Sort string for storing
# number at exact map position
str_sorted = "".join( sorted (str1))
m.setdefault(str_sorted, set ()).add(x)
# Print result
print_result(m)
# Driver Code if __name__ = = "__main__" :
# Given K
K = 2
# Function Call
anagramic_squares(K)
#This code is contributed by shivhack999 |
using System;
using System.Collections.Generic;
using System.Linq;
class AnagramicSquare
{ // Function to find the largest set of
// perfect squares which are anagram
public static void PrintResult(Dictionary< string , HashSet< long >> m)
{
// Get the first entry in the dictionary
var maxItr = m.First();
long maxi = -1;
foreach ( var entry in m) {
long siz1 = entry.Value.Count;
// Check if size of maximum set
// is less than the current set
if (maxi < siz1)
{
// Update maximum set
maxi = siz1;
maxItr = entry;
}
// If lengths are equal
else if (maxi == siz1)
{
// Update maximum set to store
// the set with maximum element
if (maxItr.Value.Max() < entry.Value.Max()) {
maxi = siz1;
maxItr = entry;
}
}
}
// Stores the max element from the set
long result = maxItr.Value.Max();
// Print final Result
Console.WriteLine(result);
}
// Function to find the
// perfect squares which are anagrams
public static void AnagramicSquares( long k)
{
// Stores the sequence
Dictionary< string , HashSet< long >> m = new Dictionary< string , HashSet< long >>();
// Initialize start and end
// of perfect squares
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);
// Iterate from start to end
for ( long i = start; i <= end; i++) {
long x = i * i;
// Converting int to string
string str = x.ToString();
if (str.Length == k) {
// Sort string for storing
// number at exact map position
char [] tempArr = str.ToCharArray();
Array.Sort(tempArr);
str = new string (tempArr);
// Insert number at map
if (!m.ContainsKey(str))
m.Add(str, new HashSet< long >());
m[str].Add(x);
}
}
// Print result
PrintResult(m);
}
// Driver Code
public static void Main( string [] args) {
// Given K
long K = 2;
// Function Call
AnagramicSquares(K);
}
} |
function anagramicSquares(k) {
// Stores the sequence
let m = new Map();
// Initialize start and end
// of perfect squares
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);
// Iterate form start to end
for (let i = start; i <= end; i++) {
let x = i * i;
// Converting int to string
let str = x.toString();
if (str.length === k) {
// Sort string for storing
// number at exact map position
let tempArr = str.split( '' ).sort();
str = tempArr.join( '' );
// Insert number at map
if (!m.has(str)) {
m.set(str, new Set());
}
m.get(str).add(x);
}
}
// Print result
printResult(m);
} // Function to find the largest set of // perfect squares which are anagram function printResult(m) {
let maxItr = Array.from(m.entries())[0];
let maxi = -1;
for (let [key, value] of m.entries()) {
let siz1 = value.size;
// Check if size of maximum set
// is less than the current set
if (maxi < siz1) {
// Update maximum set
maxi = siz1;
maxItr = [key, value];
}
// If lengths are equal
else if (maxi === siz1) {
// Update maximum set to store
// the set with maximum element
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];
}
}
}
// Stores the max element from the set
let result = Array.from(maxItr[1]).reduce((a, b) => Math.max(a, b));
// Print final Result
console.log(result);
} // Given K let K = 2; // Function Call anagramicSquares(K); |
81
Time Complexity: O(N)
Auxiliary Space: O(N)