The solution reports a space complexity of O(n) because there are at most n stack frames active at once, where n is the length of the input string.
In each of the stack frames, on line 14, we create a new swapped_str
that’s the same length as the original string, n, and remains until the frame closes.
With n frames each with a new string of length n, would our space complexity be O(n^2)? I think this approach would get us down to O(n) space:
def permute_word(word):
def recurse(word, i):
nonlocal result, n
if i == n - 1:
result.append("".join(word))
for j in range(i, n):
word[i], word[j] = word[j], word[i]
recurse(word, i + 1)
word[i], word[j] = word[j], word[i]
result = []
n = len(word)
recurse(list(word), 0)
return result
Course: Grokking Coding Interview Patterns in Python - Learn Interactively
Lesson: Solution: Permutations