Beruflich Dokumente
Kultur Dokumente
GeeksforGeeks
A computer science portal for geeks
GeeksQuiz
Login
Home
Algorithms
DS
GATE
Interview Corner
Q&A
C
C++
Java
Books
Contribute
Ask a Q
About
Array
Bit Magic
C/C++
Articles
GFacts
Linked List
MCQ
Misc
Output
String
Tree
Graph
1/21
2/27/2014
#icue<ti.>
nld sdoh
/ Fnto t sa vle a topitr *
* ucin o wp aus t w ones /
vi sa (hr*,ca *)
od wp ca x hr y
{
ca tm;
hr ep
tm =*;
ep
x
* =*;
x
y
* =tm;
y
ep
}
/ Fnto t pitpruain o srn
* ucin o rn emttos f tig
Ti fnto tkstreprmtr:
hs ucin ae he aaees
1 Srn
. tig
2 Satn idxo tesrn
. trig ne f h tig
3 Edn idxo tesrn.*
. nig ne f h tig /
vi prueca *,iti itn
od emt(hr a n , n )
{
itj
n ;
i ( = n
f i = )
pit(%\" a;
rnf"sn, )
es
le
{
fr( =i j< n j+
o j
;
= ; +)
{
sa(ai,(+);
wp(+) aj)
pruea i1 n;
emt(, +, )
sa(ai,(+);/bctak
wp(+) aj) /akrc
}
}
}
/ Die pormt ts aoefntos*
* rvr rga o et bv ucin /
itmi(
n an)
{
ca a]="B"
hr [
AC;
pruea 0 2;
emt(, , )
gthr)
eca(;
rtr 0
eun ;
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
2/21
2/27/2014
Output:
AC
B
AB
C
BC
A
BA
C
CA
B
CB
A
Related Tpoics:
Recursively remove all adjacent duplicates
Find the first non-repeating character from a stream of characters
Dynamic Programming | Set 33 (Find if a string is interleaved of two other strings)
Remove b and ac from a given string
Dynamic Programming | Set 29 (Longest Common Substring)
Write your own atoi()
String matching where one string contains wildcard characters
Count words in a given string
Like
97
Tw eet
Writing code in comment? Please use ideone.com and share the link here.
222 Comments
GeeksforGeeks
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
Login
3/21
2/27/2014
Sort by Newest
Share
Favorite
8 days ago
The solution doesn't work if the string contains duplicate charaters like 'AAB' , obviously this
case should be handled by the permutation algo.
Reply Share
Pratham
18 days ago
I wrote the code for variable length string but the program gives segmentation fault.
#include<string.h>
void swap(char *i,char *j)
{
char t;
t=*i;
*i=*j;
*j=t;
}
void perm(char *str,int i,int n)
{
int j;
if(i==n)
{
printf("%s",str);
}
else
{
for(j=i;j<=n;j++)
{
swap(str+i,str+j);
perm(str,i+1,n);
swap(str+i,str+j);
}
}
}
int main()
{
char *string;
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
4/21
2/27/2014
int n;
printf("Enter the string");
scanf("%s",string);
n=strlen(string);
perm(string,0,n);
return 0;
}
please tell me where i went wrong</string.h>
Reply Share
Javed
in the main() funcion you need to pass 1 less than strlen(string) i.e the maximum actual
index in the string i.e. n-1 to the function perm().
Reply Share
Pratham
SHANTANU AGRAWAL
http://ideone.com/WPCW48
Reply Share
Ankit
24 days ago
Can someone tell me that when I use char *temp in the swap function why doesn't my program
work?
Reply Share
sonu
When length of string is unknown ,i.e. Char array can be of any size , Pass by reference
is used .
Reply Share
Vignesh A
a month ago
The code works fine with out Back Tracking.. Please explain the logic
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
5/21
2/27/2014
Reply Share
with out backtracking ,The string order will not be changed for every iteration.
try with string "ABCD".you will find repeated patterns with B.
Once you swap the elements in the every iteration,it is better to swap the elements back
to the original order .
see this link
http://ideone.com/Cd4WUq
2
Andria
Reply Share
2 months ago
Hello everyone!I have to create a similar algorithm that records all possible rearrangements of
the characters at a string with five different characters.My program has to be general (the user
types the string). Can someone help me? Thank's!
4
Reply Share
saurabh
2 months ago
In this algorithm, if we avoid the second swap function, the program still works. Can someone
please explain this?
Reply Share
Charles
no, it won't work , try 'abcd', you can see though you still got 24 strings, some of them
are duplicated , the reason for the 2nd swap is to restore the original permutation so that
you won't have a false positive result.
Reply Share
Gaurav Ramesh
3 months ago
you could change the condition for swap to make it work for repeated characters, where the
number of permutations reduce..
for(..){
if(a+i == a+j && i != j) continue;
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
6/21
2/27/2014
Reply Share
mragrid
3 months ago
What if i want the algorithm to stop if it reaches a limit ? for example if we have 3628800 (10!)
permutations and i want it to stop when we have generated 1000 permutations ? and what time
complexity we will have that way ?
6
Reply Share
Jingguo Yao
3 months ago
Lexicographic permutation generation algorithm handles duplicated characters. See page 319
of The Art of Computer Programming, Volume 4A, Chapter 7.2.1.2.
ipr ss
mot y
MNIT=-y.ait-1
I_N
ssmxn
dflxcgahcodrgnrto()
e eiorpi_re_eeainA:
A00 =[I_N]
[:]
MNIT
Asr(
.ot)
n=lnA -1
e()
wieTu:
hl re
pit".on[t()frxi A1])
rn("ji(srx o
n [:])
j=n-1
wieAj > Aj+1:
hl [] = [
]
j- 1
=
i j= 0
f
= :
rtr
eun
l=n
wieAj > Al:
hl [] = []
l- 1
=
Aj,Al =Al,Aj
[] []
[] []
sfi =Aj1]
ufx
[+:
sfi.ees(
ufxrvre)
A=A:j+1]+sfi
[(
)
ufx
A=[,2 3
1 , ]
lxcgahcodrgnrto()
eiorpi_re_eeainA
A=ls(ABA"
it"AAC)
lxcgahcodrgnrto()
eiorpi_re_eeainA
Reply Share
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
7/21
2/27/2014
mathsmaths
3 months ago
thanks
Reply Share
DevilGeek
4 months ago
atiq
4 months ago
//Repeatation will not harm my code....like AABA ... will give result with no repeatation
http://ideone.com/acjCxb
Happy coding
5
Reply Share
Sriharsha g.r.v
Sriharsha g.r.v
5 months ago
it will not work for repeated character strings i.e "abaaa" it prints many repeated strings
6
Reply Share
Gaurav Ramesh
you can change the swap condition .. to only swap when character at i and j are not
same..
so your condition inside for will look like:
for(..){
if(a+i == a+j && i != j) continue;
// rest of the code as given..
}
Reply Share
akshita
Gaurav Ramesh
Hi Akshita,
If you've understood the main code, the change I've suggested is just to
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
8/21
2/27/2014
prevent swapping of the letters when both letters at i and j are same !
thus avoiding the repeated permutations..
Reply Share
derek
not correct,
for example 'aabb'
Reply Share
Gaurav Ramesh
Hey Derek, I don't see why this shouldn't work for your input ! when i and
j are both pointing to a or b, they shouldn't be swapped and just continue..
Reply Share
Guest
should be
if((*(char *)(a+i) == *(char *)(a+j)) && (i != j)) continue;
2
Sameer
Reply Share
5 months ago
http://codingrecipies.blogspot...
1
Reply Share
DarkProtocol
5 months ago
GuestPost
//check this
//http://www.cplusplus.com/refer...
1
Puzzled
Reply Share
5 months ago
Neha Garg
5 months ago
Reply Share
Guy
the idea is that for every N length string we can calculate the permutation of that string
by first calculating all the strings which start at the first letter of the original string + all
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
9/21
2/27/2014
by first calculating all the strings which start at the first letter of the original string + all
the permutations of the rest of the string and then the permutations of the string starts
with the second letter + all the permutations of the rest of the string and so on until we
reach the strings which starts with the last letter of the string + all the permutations of
the rest of the string .
following that logic the recursion tree grows.
the swap simply moves to the start the letter we wanted to start with and is used to
make all the changes "in place" thus not to waste extra space.
(if space is not a problem then this could also be done by creating an array of strings
and concatenating the first letter to the already generated string each time instead of the
swap).
5
Reply Share
Bharath G M
Reply Share
6 months ago
Reply Share
Bharath G M
Nhan
6 months ago
Reply Share
6 months ago
what is the need of backtrack step here?? answer is still correct without this step..
1
Reply Share
Marsha Donna
the need 4 backtracking is to always work with the original string..in the second iteration
after a and b are swapped the string becomes bac..when the function is recurively
called..the permutation of bac keepin b fixed are Bac and Bca...if we leave the string as
bca..in the next iteration when we have to swap a and c(in original string abc) to form
cba it would not be possible correctly unless we revert Bca back to bac...then it would
go back change bac to the original string abc after which a and c are swapped to cba for
the next iteration...see the figure above
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
10/21
2/27/2014
Pranjal
Its correct for the ABC case --- Try it with 4 characters and you will see the importance
of backtracking !!!
8
Guest
Reply Share
6 months ago
/ TeTDLcp:Dfnsteetypitfrtecnoeapiain
/ reoL.p
eie h nr on o h osl plcto.
#nld "taxh
icue sdf."
#nld <otem
icue isra>
uignmsaesd
sn aepc t;
src Nd
tut oe
{
itdt;
n aa
Nd *et
oe lf;
Nd *ih;
oe rgt
}
;
casTe
ls re
{
sai itl
ttc n ;
sai itfi;
ttc n lp
sai itladph
ttc n efet;
sai Nd *pe;
ttc oe
rv
sai Nd *peiu;
ttc oe
rvos
sai itcut
ttc n on;
pbi:
ulc
Nd *ed
oe ha;
itmxet;
n adph
Te(
re)
{
ha =NL;
ed
UL
mxet =0
adph
;
}
vi IodrNd *oe
od nre(oe nd)
{
i(oe
fnd)
{
Iodrnd-lf)
nre(oe>et;
sd:ot< ["<oe>aa< " ]"
t:cu<"
<nd-dt <
;
Iodrnd-rgt;
nre(oe>ih)
}
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
11/21
2/27/2014
}
vi TetDLNd *oe
od reoL(oe nd)
{
i(oe
fnd)
{
TetDLnd-lf)
reoL(oe>et;
i(rvos
fpeiu)
{
peiu-rgt=nd;
rvos>ih
oe
nd-lf =peiu;
oe>et
rvos
}
i(on = 0
fcut = )
{
ha =nd;
ed
oe
cut=cut+1
on
on
;
}
peiu =nd;
rvos
oe
TetDLnd-rgt;
reoL(oe>ih)
}
}
vi PitL(
od rnDL)
{
Nd *m =ha;
oe tp
ed
wietp
hl(m)
{
sd:ot<m-dt;
t:cu<tp>aa
tp=tp>ih;
m
m-rgt
}
}
vi IsrNd(oe*oeitdt)
od netoeNd nd,n aa
{
Nd *tp=nd;
oe
m
oe
i(ed= NL)
fha = UL
{
ha =nwNd;
ed
e oe
ha-dt =dt;
ed>aa
aa
ha-lf =NL;
ed>et
UL
ha-rgt=NL;
ed>ih
UL
rtr;
eun
}
es i(m)
le ftp
{
pe =tp
rv
m;
i(aa>tp>aa
fdt
m-dt)
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
12/21
2/27/2014
i(aa>tp>aa
fdt
m-dt)
{
l0
=;
tp=tp- rgt
m
m > ih;
IsrNd(m,aa;
netoetpdt)
}
es
le
{
l1
=;
IsrNd(m-lf,aa;
netoetp>etdt)
}
}
i( = 1
fl = )
{
pe-lf =nwNd;
rv>et
e oe
pe-lf-dt =dt;
rv>et>aa
aa
pe-lf-lf =NL;
rv>et>et
UL
pe-lf-rgt=NL;
rv>et>ih
UL
l=-;
1
rtr;
eun
}
es i( = 0
le fl = )
{
pe-rgt=nwNd;
rv>ih
e oe
pe-rgt>aa=dt;
rv>ih-dt
aa
pe-rgt>et=NL;
rv>ih-lf
UL
pe-rgt>ih =NL;
rv>ih-rgt
UL
l=-;
1
rtr;
eun
}
}
}
;
itTe:l=;
n re: 0
itTe:fi =;
n re:lp 0
itTe:ladph=1
n re:efet -;
itTe:cut=0
n re:on
;
Nd *Te:pe =NL;
oe
re:rv
UL
Nd *Te:peiu =NL;
oe
re:rvos
UL
itmi(n ag,ca*ag[)
n anit rc hr rv]
{
Te t
re ;
tIsrNd(.ed1)
.netoetha,0;
tIsrNd(.ed7;
.netoetha,)
tIsrNd(.ed1)
.netoetha,3;
tIsrNd(.ed5;
.netoetha,)
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
13/21
2/27/2014
tIsrNd(.ed5;
.netoetha,)
tIsrNd(.ed9;
.netoetha,)
tIsrNd(.ed1)
.netoetha,2;
tIsrNd(.ed1)
.netoetha,5;
tIsrNd(.ed3;
.netoetha,)
tIsrNd(.ed6;
.netoetha,)
tIsrNd(.ed8;
.netoetha,)
tIsrNd(.ed1)
.netoetha,1;
tIsrNd(.ed1;
.netoetha,)
tIsrNd(.ed4;
.netoetha,)
tIsrNd(.ed2;
.netoetha,)
tTetDLtha)
.reoL(.ed;
tPitL(;
.rnDL)
rtr 0
eun ;
}
<tp>/oe>/otem
/m-<nd-<isra>
Reply Share
raghvendra
6 months ago
#nld <otem
icue isra>
#nld<tlbh
icuesdi.>
#nld<srn>
icuectig
uignmsaesd
sn aepc t;
ca sr10;
hr t[0]
vi pruainitn
od emtto(n )
{
ca x
hr ;
i(<0
fn=)
{
cu<sr<nl
ot<t<ed;
rtr;
eun
}
friti0ini+
o(n =;<;+)
{
xsri;
=t[]
sri=t[-]
t[]srn1;
srn1=;
t[-]x
pruainn1;
emtto(-)
xsri;
=t[]
sri=t[-]
t[]srn1;
srn1=;
t[-]x
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
14/21
2/27/2014
srn1=;
t[-]x
}
}
itmi(
n an)
{
cn>t;
i>sr
Reply Share
EDGE
The output size is too large (infinite loop or larger text output).
Reply Share
nomank
7 months ago
[sourcecode language="JAVA"]
public class StringPermutation {
public static void main(String[] args) {
stringPermutation("TESTPERMUTATION");
}
public static void stringPermutation(String str) {
if (str == null )
return;
doPermutation("", str);
}
public static void doPermutation(String prefix, String str) {
if (str.length() == 1) {
System.out.println(prefix + str);
return;
}
for (int i = 0; i < str.length(); i++) {
doPermutation(prefix + str.charAt(i), removeCharAt(str,i));
}
}
public static String removeCharAt(String str, int index) {
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(index);
return sb.toString();
}
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
15/21
2/27/2014
}
}
4
Reply Share
7 months ago
Reply Share
7 months ago
16/21
2/27/2014
ptr->str=temp;
strcpy(ptr->str, str);
see more
Reply Share
Irfanali117
7 months ago
pbi casprue{
ulc ls emt
Raj Kishor
7 months ago
[sourcecode language="C++"]
//permutation of a string
#include<iostream>
#include<string>
using namespace std;
void permute(string ,string , int);
int main()
{
string str="",dats;
cout<<"String: ";
cin>>dats;
cout<<"The Permutations of \'"<<dats<<"\' are..."<<endl;
permute(str,dats,0);
}
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
17/21
2/27/2014
7 months ago
vishal
7 months ago
//In C#....
public static void permutation(string strPrefix, string str)
{
int n = str.Length;
if(n == 1)
Console.WriteLine(strPrefix + str);
for (int i = 0; i < str.Length; i++)
{
string prefix = strPrefix + str.Substring(i, 1);
permutation(prefix, str.Substring(0,i) + str.Substring(i+1,n-i-1));
}
}
1
Reply Share
rajashekar007
7 months ago
Subscribe
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
18/21
2/27/2014
Interview Experiences
Advanced Data Structures
Dynamic Programming
Greedy Algorithms
Backtracking
Pattern Searching
Divide & Conquer
Mathematical Algorithms
Recursion
Geometric Algorithms
Popular Posts
All permutations of a given string
Memory Layout of C Programs
Understanding extern keyword in C
Median of two sorted arrays
Tree traversal without recursion and without stack!
Structure Member Alignment, Padding and Data Packing
Intersection point of two Linked Lists
Lowest Common Ancestor in a BST.
Check if a binary tree is BST or not
Sorted Linked List to Balanced BST
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
19/21
2/27/2014
655
Subscribe
Recent Comments
gagan
for question i think answer should be D as An...
Database Management Systems | Set 2 5 minutes ago
Debabrata Bardhan
#include<iostream> #define BUFSIZE 5 struct...</iostream>
Pairwise swap elements of a given linked list by changing links 15 minutes ago
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
20/21
2/27/2014
alien
awesome algorithm.. can it be done inplace with...
Median in a stream of integers (running integers) 5 hours ago
Kid of Kop
I hope this helps, k = 0 is a special case......
Print all nodes that are at distance k from a leaf node 6 hours ago
Kid of Kop
I accept. code works only in balanced trees
Print all nodes that are at distance k from a leaf node 6 hours ago
Joel
Here's an implementation although not memoized...
Dynamic Programming | Set 4 (Longest Common Subsequence) 6 hours ago
C++
String C
C++ Code Compare String Print
C++ Find String
String Search
http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
21/21