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 skyInput: 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:
#include <algorithm> #include <iostream> #include <vector> // Function to generate permutations using generators 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;
} // Function to generate permutations of all words in a // sentence void calculatePermutations(std::string sentence)
{ // Stores all words in the sentence
std::vector<std::string> words;
// Split the sentence into 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));
// Stores all possible permutations of words in this
// vector
auto permutations = permuteGenerator(words);
// Iterate over all permutations
for ( const auto & permutation : permutations) {
// Print the words in the vector separated by spaces
for ( const auto & word : permutation) {
std::cout << word << " " ;
}
std::cout << std::endl;
}
} // Driver Code int main()
{ std::string sentence = "sky is blue" ;
calculatePermutations(sentence);
return 0;
} |
import java.util.*;
public class Main {
// Function to generate permutations
// of all words in a sentence
public static void calculatePermutations(String sentence) {
// Stores all words in the sentence
String[] lis = sentence.split( " " );
// Stores all possible permutations
// of words in this list
Iterable<String[]> permute = permuteGenerator(lis);
// Iterate over all permutations
for (String[] i : permute) {
// Print the words in the
// list separated by spaces
System.out.println(String.join( " " , i));
}
}
// Function to generate permutations using generators
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;
}
}
// Driver Code
public static void main(String[] args) {
String sentence = "sky is blue" ;
calculatePermutations(sentence);
}
} |
# Python implementation of # the above approach from itertools import permutations
# Function to generate permutations # of all words in a sentence def calculatePermutations(sentence):
# Stores all words in the sentence
lis = list (sentence.split())
# Stores all possible permutations
# of words in this list
permute = permutations(lis)
# Iterate over all permutations
for i in permute:
# Convert the current
# permutation into a list
permutelist = list (i)
# Print the words in the
# list separated by spaces
for j in permutelist:
print (j, end = " " )
# Print a new line
print ()
# Driver Code if __name__ = = '__main__' :
sentence = "sky is blue"
calculatePermutations(sentence)
|
using System;
using System.Collections.Generic;
class MainClass {
// Function to generate permutations
// of all words in a sentence
static void calculatePermutations( string sentence)
{
// Stores all words in the sentence
string [] lis = sentence.Split( ' ' );
// Stores all possible permutations
// of words in this list
IEnumerable< string []> permute
= permuteGenerator(lis);
// Iterate over all permutations
foreach ( string [] i in permute)
{
// Print the words in the
// list separated by spaces
Console.WriteLine( string .Join( " " , i));
}
}
// Function to generate permutations using generators
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;
}
}
}
// Driver Code
public static void Main( string [] args)
{
string sentence = "sky is blue" ;
calculatePermutations(sentence);
}
} // This code is contributed by user_dtewbxkn77n |
// JavaScript implementation of // the above approach // Function to generate permutations // of all words in a sentence function calculatePermutations(sentence) {
// Stores all words in the sentence
let lis = sentence.split( " " );
// Stores all possible permutations
// of words in this list
let permute = permuteGenerator(lis);
// Iterate over all permutations
for (let i of permute) {
// Print the words in the
// list separated by spaces
console.log(i.join( " " ));
}
} // Function to generate permutations using generators 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]];
}
} // Driver Code let sentence = "sky is blue" ;
calculatePermutations(sentence); // This code is contributed by adityashae15 |
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:
#include <iostream> #include <vector> #include <algorithm> class Main {
public :
// Function to generate permutations of the all words in a sentence
static void GFG(std::string sentence) {
// Stores all words in the 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;
// Generate all permutations of words
generatePermutations(lis, 0, permute);
// Iterate over all permutations
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;
}
}
// Function to generate all permutations using the backtracking
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 ;
}
// Iterate over the remaining words and generate permutations
for ( int i = index; i < arr.size(); i++) {
// Swap the current word with the ith word
std::swap(arr[i], arr[index]);
generatePermutations(arr, index + 1, permute);
// Swap back the current word with previously swapped word.
std::swap(arr[i], arr[index]);
}
}
}; // Driver Code int main() {
std::string sentence = "sky is blue" ;
Main::GFG(sentence);
return 0;
} |
import java.util.*;
public class Main {
// Function to generate permutations
// of all words in a sentence
public static void
calculatePermutations(String sentence)
{
// Stores all words in the sentence
String[] lis = sentence.split( " " );
// Stores all possible permutations
// of words in this list
List<String[]> permute = new ArrayList<>();
// Generate all permutations of words
generatePermutations(lis, 0 , permute);
// Iterate over all permutations
for (String[] i : permute) {
// Print the words in the
// list separated by spaces
System.out.println(String.join( " " , i));
}
}
// Function to generate all permutations using
// backtracking
public static void
generatePermutations(String[] arr, int index,
List<String[]> permute)
{
// Base case: If the current index is equal to the
// length of the array add the current permutation
// to the list of permutations
if (index == arr.length) {
permute.add(Arrays.copyOf(arr, arr.length));
return ;
}
// Iterate over the remaining words and generate
// permutations
for ( int i = index; i < arr.length; i++) {
// Swap the current word with the ith word
String temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
// Make a recursive call to generate
// permutations with the updated list and index
generatePermutations(arr, index + 1 , permute);
// Swap back the current word with the
// previously swapped word
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
// Driver Code
public static void main(String[] args)
{
String sentence = "sky is blue" ;
calculatePermutations(sentence);
}
} // This code is contributed by sarojmcy2e |
from typing import List
# Function to generate permutations of all words in a sentence def calculatePermutations(sentence: str ) - > None :
# Stores all words in the sentence
lis = sentence.split( " " )
# Stores all possible permutations of words in this list
permute = []
# Generate all permutations of words
generatePermutations(lis, 0 , permute)
# Iterate over all permutations
for i in permute:
# Print the words in the list separated by spaces
print ( " " .join(i))
# Function to generate all permutations using backtracking def generatePermutations(arr: List [ str ], index: int , permute: List [ List [ str ]]) - > None :
# Base case: If the current index is equal to the length of the array,
# add the current permutation to the list of permutations
if index = = len (arr):
permute.append(arr.copy())
return
# Iterate over the remaining words and generate permutations
for i in range (index, len (arr)):
# Swap the current word with the ith word
arr[i], arr[index] = arr[index], arr[i]
# Make a recursive call to generate permutations with the updated list and index
generatePermutations(arr, index + 1 , permute)
# Swap back the current word with the previously swapped word
arr[i], arr[index] = arr[index], arr[i]
# Driver Code if __name__ = = "__main__" :
sentence = "sky is blue"
calculatePermutations(sentence)
|
using System;
using System.Collections.Generic;
class GFG {
// Function to generate permutations
// of all words in a sentence
public static void
CalculatePermutations( string sentence)
{
// Stores all words in the sentence
string [] lis = sentence.Split( ' ' );
// Stores all possible permutations
// of words in this list
List< string []> permute = new List< string []>();
// Generate all permutations of words
GeneratePermutations(lis, 0, permute);
// Iterate over all permutations
foreach ( string [] i in permute)
{
// Print the words in the
// list separated by spaces
Console.WriteLine( string .Join( " " , i));
}
}
// Function to generate all permutations using
// backtracking
public static void
GeneratePermutations( string [] arr, int index,
List< string []> permute)
{
// Base case: If the current index is equal to the
// length of the array add the current permutation
// to the list of permutations
if (index == arr.Length) {
permute.Add(( string [])arr.Clone());
return ;
}
// Iterate over the remaining words and generate
// permutations
for ( int i = index; i < arr.Length; i++) {
// Swap the current word with the ith word
string temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
// Make a recursive call to generate
// permutations with the updated list and index
GeneratePermutations(arr, index + 1, permute);
// Swap back the current word with the
// previously swapped word
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
// Driver Code
public static void Main( string [] args)
{
string sentence = "sky is blue" ;
CalculatePermutations(sentence);
}
} |
// Function to generate permutations of all words in a sentence function calculatePermutations(sentence) {
// Stores all words in the sentence
const words = sentence.split( " " );
// Stores all possible permutations of words in this list
const permutations = [];
// Generate all permutations of words
generatePermutations(words, 0, permutations);
// Iterate over all permutations
for (const permutation of permutations) {
// Print the words in the list separated by spaces
console.log(permutation.join( " " ));
}
} // Function to generate all permutations using backtracking function generatePermutations(arr, index, permutations) {
// Base case: If the current index is equal to the
// length of the array, add the current permutation
// to the list of permutations
if (index === arr.length) {
permutations.push([...arr]);
return ;
}
// Iterate over the remaining words and generate permutations
for (let i = index; i < arr.length; i++) {
// Swap the current word with the ith word
const temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
// Make a recursive call to generate permutations
// with the updated list and index
generatePermutations(arr, index + 1, permutations);
// Swap back the current word with the previously swapped word
arr[index] = arr[i];
arr[i] = temp;
}
} // Driver Code const sentence = "sky is blue" ;
calculatePermutations(sentence); |
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.