python - How do I find all possible permutations of a string with only single swap? -


the complexity should o(n) n length of string. ex: 'abc', answer 'bac', 'cba', 'acb'. 'bca' , 'cab' should not in list 2 swaps required convert 'abc'.

i have made o(n2) algorithm slow.

def f(s):     temp=list(s)     l=[]     in range(len(s)):         j in range(len(s)):             temp=list(s)             temp[i],temp[j]=temp[j],temp[i]             l.append("".join(str(i) in temp))     print set(l) 

the number of possible outcomes string (with distinct characters) of length n nc2 = n * (n-1) / 2, since can choose 2 letters @ 2 indices , swap them.

hence, if plan print of outcomes, complexity o(n^2) , o(n) solution not possible.

for duplicate characters, reasoning becomes more complex. suppose there 1 duplicate character repeated k times. there n-k swaps identical. if there 1 character repeated, , repeated k times, number of possibilities nc2 - (n-k). can extended more repeated characters using inclusion-exclusion principle.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -