String which when repeated exactly K times gives a permutation of S
Given an integer K and a string str of lowercase English characters, the task is to find a string s such that when s is repeated exactly K times, it gives a permutation of S. If no such string exists, print -1.
Examples:
Input: str = “aabb”, k = 2
Output: ab
“ab” when repeated 2 times gives “abab” which is a permutation of “aabb”
Input: str = “aabb”, k = 3
Output: -1
Approach 1 : Using Map and Sorting
In this approach, we will make use of a map to store the frequency of each character in the string.
We will then sort the map based on the frequency of the characters in decreasing order. Finally, we
will iterate through the map and check if the frequency of each character is divisible by k. If yes,
then we will append the character to the answer string k times. If any character's frequency is not
divisible by k, we return -1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string K_String(string s, int k)
{
int n = s.size();
map< char , int > freq;
for ( int i = 0; i < n; i++)
freq[s[i]]++;
string str = "" ;
vector<pair< char , int > > sorted_freq(freq.begin(),
freq.end());
sort(sorted_freq.begin(), sorted_freq.end(),
[]( const pair< char , int >& a,
const pair< char , int >& b) {
return a.second > b.second;
});
for ( auto it : sorted_freq) {
char c = it.first;
int f = it.second;
if (f % k == 0) {
int x = f / k;
while (x--) {
str += c;
}
}
else {
return "-1" ;
}
}
return str;
}
int main()
{
string s = "aabb" ;
int k = 2;
cout << K_String(s, k);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static String K_String(String s, int k)
{
int n = s.length();
Map<Character, Integer> freq = new HashMap<>();
for ( int i = 0 ; i < n; i++) {
char c = s.charAt(i);
freq.put(c, freq.getOrDefault(c, 0 ) + 1 );
}
StringBuilder str = new StringBuilder();
List<Map.Entry<Character, Integer> > sorted_freq
= new ArrayList<>(freq.entrySet());
Collections.sort(
sorted_freq,
new Comparator<
Map.Entry<Character, Integer> >() {
@Override
public int compare(
Map.Entry<Character, Integer> a,
Map.Entry<Character, Integer> b)
{
return b.getValue().compareTo(
a.getValue());
}
});
for (Map.Entry<Character, Integer> entry :
sorted_freq) {
char c = entry.getKey();
int f = entry.getValue();
if (f % k == 0 ) {
int x = f / k;
while (x-- > 0 ) {
str.append(c);
}
}
else {
return "-1" ;
}
}
return str.toString();
}
public static void main(String[] args)
{
String s = "aabb" ;
int k = 2 ;
System.out.println(K_String(s, k));
}
}
|
Python3
def K_String(s, k):
n = len (s)
freq = {}
for i in range (n):
if s[i] in freq:
freq[s[i]] + = 1
else :
freq[s[i]] = 1
str = ""
sorted_freq = sorted (freq.items(), key = lambda x: x[ 1 ], reverse = True )
for it in sorted_freq:
c = it[ 0 ]
f = it[ 1 ]
if f % k = = 0 :
x = f / / k
while x > 0 :
str + = c
x - = 1
else :
return "-1"
return str
s = "aabb"
k = 2
print (K_String(s, k))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
public static string K_String( string s, int k)
{
int n = s.Length;
Dictionary< char , int > freq
= new Dictionary< char , int >();
foreach ( char c in s) freq = 0;
foreach ( char c in s) freq++;
string str = "" ;
var sorted_freq
= freq.OrderByDescending(item => item.Value);
foreach ( var item in sorted_freq)
{
char c = item.Key;
int f = item.Value;
if (f % k == 0) {
int x = f / k;
while (x > 0) {
str += c;
x--;
}
}
else {
return "-1" ;
}
}
return str;
}
public static void Main( string [] args)
{
string s = "aabb" ;
int k = 2;
Console.WriteLine(K_String(s, k));
}
}
|
Javascript
function K_String(s, k) {
let n = s.length;
let freq = new Map();
for (let i = 0; i < n; i++) {
if (freq.has(s[i])) {
freq.set(s[i], freq.get(s[i]) + 1);
} else {
freq.set(s[i], 1);
}
}
let str = "" ;
let sorted_freq = Array.from(freq.entries());
sorted_freq.sort((a, b) => b[1] - a[1]);
for (let it of sorted_freq) {
let c = it[0];
let f = it[1];
if (f % k === 0) {
let x = f / k;
while (x--) {
str += c;
}
}
else {
return "-1" ;
}
}
return str;
}
let s = "aabb" ;
let k = 2;
console.log(K_String(s, k));
|
Output :
ab
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Approach 2: An efficient approach is to count the frequency of each character of the given string. If the frequency of any character is not divisible by k then the solution is not possible and print -1. Otherwise, add every character (frequency / k) times to the resultant string and print the generated string in the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string K_String(string s, int k)
{
int n = s.size();
int fre[26] = { 0 };
for ( int i = 0; i < n; i++)
fre[s[i] - 'a' ]++;
string str = "" ;
for ( int i = 0; i < 26; i++) {
if (fre[i] % k == 0) {
int x = fre[i] / k;
while (x--) {
str += ( char )(i + 'a' );
}
}
else {
return "-1" ;
}
}
return str;
}
int main()
{
string s = "aabb" ;
int k = 2;
cout << K_String(s, k);
return 0;
}
|
Java
class GfG {
static String K_String(String s, int k)
{
int n = s.length();
int fre[] = new int [ 26 ];
for ( int i = 0 ; i < n; i++)
fre[s.charAt(i) - 'a' ]++;
String str = "" ;
for ( int i = 0 ; i < 26 ; i++) {
if (fre[i] % k == 0 ) {
int x = fre[i] / k;
while (x != 0 ) {
str += ( char )(i + 'a' );
x--;
}
}
else {
return "-1" ;
}
}
return str;
}
public static void main(String[] args)
{
String s = "aabb" ;
int k = 2 ;
System.out.println(K_String(s, k));
}
}
|
Python 3
def K_String(s, k):
n = len (s)
fre = [ 0 ] * 26
for i in range (n):
fre[ ord (s[i]) - ord ( 'a' )] + = 1
str = ""
for i in range ( 26 ):
if (fre[i] % k = = 0 ):
x = fre[i] / / k
while (x):
str + = chr (i + ord ( 'a' ))
x - = 1
else :
return "-1"
return str
if __name__ = = "__main__" :
s = "aabb"
k = 2
print (K_String(s, k))
|
C#
using System;
class GFG {
static String K_String(String s, int k)
{
int n = s.Length;
int [] fre = new int [26];
for ( int i = 0; i < n; i++)
fre[s[i] - 'a' ]++;
String str = "" ;
for ( int i = 0; i < 26; i++) {
if (fre[i] % k == 0) {
int x = fre[i] / k;
while (x != 0) {
str += ( char )(i + 'a' );
x--;
}
}
else {
return "-1" ;
}
}
return str;
}
public static void Main(String[] args)
{
String s = "aabb" ;
int k = 2;
Console.WriteLine(K_String(s, k));
}
}
|
Javascript
<script>
function K_String(s,k)
{
let n = s.length;
let fre = new Array(26);
for (let i=0;i<fre.length;i++)
{
fre[i]=0;
}
for (let i = 0; i < n; i++)
fre[s[i].charCodeAt(0) - 'a' .charCodeAt(0)]++;
let str = "" ;
for (let i = 0; i < 26; i++) {
if (fre[i] % k == 0) {
let x = Math.floor(fre[i] / k);
while (x != 0) {
str += String.fromCharCode(i + 'a' .charCodeAt(0));
x--;
}
}
else {
return "-1" ;
}
}
return str;
}
let s = "aabb" ;
let k = 2;
document.write(K_String(s, k));
</script>
|
PHP
<?php
function K_String( $s , $k )
{
$n = strlen ( $s );
$fre = $array = array_fill (0, 26, 0);
for ( $i = 0; $i < $n ; $i ++)
$fre [ord( $s [ $i ]) - ord( 'a' )]++;
$str = "" ;
for ( $i = 0; $i < 26; $i ++)
{
if ( $fre [ $i ] % $k == 0)
{
$x = $fre [ $i ] / $k ;
while ( $x --)
{
$str .= chr ( $i + ord( 'a' ));
}
}
else
{
return "-1" ;
}
}
return $str ;
}
$s = "aabb" ;
$k = 2;
echo K_String( $s , $k );
?>
|
Time Complexity: O(n)
Space Complexity: O(1)
Last Updated :
18 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...