Generate all possible permutations of words in a Sentence
Given a string S, the task is to print permutations of all words in a sentence.
Examples:
Input: S = “sky is blue”
Output:
sky is blue
sky blue is
is sky blue
is blue sky
blue sky is
blue is sky
Input: S =” Do what you love”
Output:
Do what you love
Do what love you
Do you what love
Do you love what
Do love what you
Do love you what
what Do you love
what Do love you
what you Do love
what you love Do
what love Do you
what love you Do
you Do what love
you Do love what
you what Do love
you what love Do
you love Do what
you love what Do
love Do what you
love Do you what
love what Do you
love what you Do
love you Do what
love you what Do
Approach: The given problem can be solved using recursion. Follow the steps below to solve the problem:
- Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list.
- Permute the list using built-in python functions itertools.permutations().
- Traverse the permutations and convert each permutation to a list.
- Print these lists.
Below is the implementation of the above approach:
C++
#include <algorithm>
#include <iostream>
#include <vector>
std::vector<std::vector<std::string> >
permuteGenerator(std::vector<std::string> arr, int n = -1)
{
std::vector<std::vector<std::string> > result;
if (n == -1)
n = arr.size();
if (n <= 1) {
result.push_back(arr);
}
else {
for ( int i = 0; i < n; i++) {
auto subPermutations
= permuteGenerator(arr, n - 1);
for ( const auto & k : subPermutations) {
result.push_back(k);
}
int j = (n % 2 != 0) ? 0 : i;
std::swap(arr[j], arr[n - 1]);
}
}
return result;
}
void calculatePermutations(std::string sentence)
{
std::vector<std::string> words;
size_t start = 0, end;
while ((end = sentence.find( ' ' , start))
!= std::string::npos) {
words.push_back(
sentence.substr(start, end - start));
start = end + 1;
}
words.push_back(sentence.substr(start));
auto permutations = permuteGenerator(words);
for ( const auto & permutation : permutations) {
for ( const auto & word : permutation) {
std::cout << word << " " ;
}
std::cout << std::endl;
}
}
int main()
{
std::string sentence = "sky is blue" ;
calculatePermutations(sentence);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void calculatePermutations(String sentence) {
String[] lis = sentence.split( " " );
Iterable<String[]> permute = permuteGenerator(lis);
for (String[] i : permute) {
System.out.println(String.join( " " , i));
}
}
public static Iterable<String[]> permuteGenerator(String[] arr) {
return permuteGenerator(arr, arr.length);
}
public static Iterable<String[]> permuteGenerator(String[] arr, int n) {
if (n <= 1 ) {
List<String[]> result = new ArrayList<>();
result.add(Arrays.copyOf(arr, arr.length));
return result;
} else {
List<String[]> result = new ArrayList<>();
for (String[] i : permuteGenerator(arr, n - 1 )) {
result.add(Arrays.copyOf(i, i.length));
}
for ( int i = 0 ; i < n - 1 ; i++) {
if (n % 2 == 0 ) {
String temp = arr[i];
arr[i] = arr[n - 1 ];
arr[n - 1 ] = temp;
} else {
String temp = arr[ 0 ];
arr[ 0 ] = arr[n - 1 ];
arr[n - 1 ] = temp;
}
for (String[] k : permuteGenerator(arr, n - 1 )) {
result.add(Arrays.copyOf(k, k.length));
}
}
return result;
}
}
public static void main(String[] args) {
String sentence = "sky is blue" ;
calculatePermutations(sentence);
}
}
|
Python3
from itertools import permutations
def calculatePermutations(sentence):
lis = list (sentence.split())
permute = permutations(lis)
for i in permute:
permutelist = list (i)
for j in permutelist:
print (j, end = " " )
print ()
if __name__ = = '__main__' :
sentence = "sky is blue"
calculatePermutations(sentence)
|
C#
using System;
using System.Collections.Generic;
class MainClass {
static void calculatePermutations( string sentence)
{
string [] lis = sentence.Split( ' ' );
IEnumerable< string []> permute
= permuteGenerator(lis);
foreach ( string [] i in permute)
{
Console.WriteLine( string .Join( " " , i));
}
}
static IEnumerable< string []>
permuteGenerator( string [] arr, int n = -1)
{
if (n == -1)
n = arr.Length;
if (n <= 1) {
yield return arr;
}
else {
for ( int i = 0; i < n; i++) {
foreach ( string [] k in permuteGenerator(
arr, n - 1))
{
yield return k;
}
int j = n % 2 != 0 ? 0 : i;
string temp = arr[j];
arr[j] = arr[n - 1];
arr[n - 1] = temp;
}
}
}
public static void Main( string [] args)
{
string sentence = "sky is blue" ;
calculatePermutations(sentence);
}
}
|
Javascript
function calculatePermutations(sentence) {
let lis = sentence.split( " " );
let permute = permuteGenerator(lis);
for (let i of permute) {
console.log(i.join( " " ));
}
}
function * permuteGenerator(arr, n = arr.length) {
if (n <= 1) yield arr.slice();
else
for (let i = 0; i < n; i++) {
yield* permuteGenerator(arr, n - 1);
const j = n % 2 ? 0 : i;
[arr[n - 1], arr[j]] = [arr[j], arr[n - 1]];
}
}
let sentence = "sky is blue" ;
calculatePermutations(sentence);
|
Output
sky is blue
sky blue is
is sky blue
is blue sky
blue sky is
blue is sky
Time Complexity: O(N!), where N denotes the number of words in a sentence.
Auxiliary Space: O(N!)
Another Approach: Using Backtracking:
- Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list.
- Initialize an empty list to store the permutations of the words.
- Start a backtracking function to generate all possible permutations of the words list. The function will take the following parameters:
.The current list of words.
.The index of the word that needs to be swapped with the remaining words.
.The list to store the permutations of the words.
- If the current index is equal to the length of the words list, then add the current permutation to the list of permutations.
- Iterate over the remaining words from the current index to the end of the list, swapping the current word with each remaining word and making a recursive call to the backtracking function with the updated list and index.
- After the recursive call, swap back the current word with the previously swapped word.
- Return the list of permutations after all recursive calls have been made.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
#include <algorithm>
class Main {
public :
static void GFG(std::string sentence) {
std::vector<std::string> lis;
size_t pos = 0;
std::string token;
while ((pos = sentence.find( ' ' )) != std::string::npos) {
token = sentence.substr(0, pos);
lis.push_back(token);
sentence.erase(0, pos + 1);
}
lis.push_back(sentence);
std::vector<std::vector<std::string>> permute;
generatePermutations(lis, 0, permute);
for ( const auto & i : permute) {
for ( size_t j = 0; j < i.size(); ++j) {
std::cout << i[j];
if (j < i.size() - 1) {
std::cout << " " ;
}
}
std::cout << std::endl;
}
}
static void generatePermutations(std::vector<std::string>& arr, int index, std::vector<std::vector<std::string>>& permute) {
if (index == arr.size()) {
permute.push_back(arr);
return ;
}
for ( int i = index; i < arr.size(); i++) {
std::swap(arr[i], arr[index]);
generatePermutations(arr, index + 1, permute);
std::swap(arr[i], arr[index]);
}
}
};
int main() {
std::string sentence = "sky is blue" ;
Main::GFG(sentence);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void
calculatePermutations(String sentence)
{
String[] lis = sentence.split( " " );
List<String[]> permute = new ArrayList<>();
generatePermutations(lis, 0 , permute);
for (String[] i : permute) {
System.out.println(String.join( " " , i));
}
}
public static void
generatePermutations(String[] arr, int index,
List<String[]> permute)
{
if (index == arr.length) {
permute.add(Arrays.copyOf(arr, arr.length));
return ;
}
for ( int i = index; i < arr.length; i++) {
String temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
generatePermutations(arr, index + 1 , permute);
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
public static void main(String[] args)
{
String sentence = "sky is blue" ;
calculatePermutations(sentence);
}
}
|
Python3
from typing import List
def calculatePermutations(sentence: str ) - > None :
lis = sentence.split( " " )
permute = []
generatePermutations(lis, 0 , permute)
for i in permute:
print ( " " .join(i))
def generatePermutations(arr: List [ str ], index: int , permute: List [ List [ str ]]) - > None :
if index = = len (arr):
permute.append(arr.copy())
return
for i in range (index, len (arr)):
arr[i], arr[index] = arr[index], arr[i]
generatePermutations(arr, index + 1 , permute)
arr[i], arr[index] = arr[index], arr[i]
if __name__ = = "__main__" :
sentence = "sky is blue"
calculatePermutations(sentence)
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static void
CalculatePermutations( string sentence)
{
string [] lis = sentence.Split( ' ' );
List< string []> permute = new List< string []>();
GeneratePermutations(lis, 0, permute);
foreach ( string [] i in permute)
{
Console.WriteLine( string .Join( " " , i));
}
}
public static void
GeneratePermutations( string [] arr, int index,
List< string []> permute)
{
if (index == arr.Length) {
permute.Add(( string [])arr.Clone());
return ;
}
for ( int i = index; i < arr.Length; i++) {
string temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
GeneratePermutations(arr, index + 1, permute);
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
public static void Main( string [] args)
{
string sentence = "sky is blue" ;
CalculatePermutations(sentence);
}
}
|
Javascript
function calculatePermutations(sentence) {
const words = sentence.split( " " );
const permutations = [];
generatePermutations(words, 0, permutations);
for (const permutation of permutations) {
console.log(permutation.join( " " ));
}
}
function generatePermutations(arr, index, permutations) {
if (index === arr.length) {
permutations.push([...arr]);
return ;
}
for (let i = index; i < arr.length; i++) {
const temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
generatePermutations(arr, index + 1, permutations);
arr[index] = arr[i];
arr[i] = temp;
}
}
const sentence = "sky is blue" ;
calculatePermutations(sentence);
|
Output
sky is blue
sky blue is
is sky blue
is blue sky
blue is sky
blue sky is
Time Complexity: O(n! * n), where n is the number of words in the sentence.
Auxiliary Space: O(n! * n), because we are storing all possible permutations of the words in the sentence in a vector of vectors.
Last Updated :
09 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...