I am trying to figure out how the complexity of a code(from Cracking the Coding Interview book) for generating all the permutations of a given string is O(n!).
I know that that's the best possible complexity as we have n! permutations but I would like to understand it codewise, because not every algorithm that does this would be O(n!).
The Code :
import java.util.*; public class QuestionA { public static ArrayList<String> getPerms(String str) { if (str == null) { return null; } ArrayList<String> permutations = new ArrayList<String>(); if (str.length() == 0) { // base case permutations.add(""); return permutations; } char first = str.charAt(0); // get the first character String remainder = str.substring(1); // remove the first character ArrayList<String> words = getPerms(remainder); for (String word : words) { for (int j = 0; j <= word.length(); j++) { String s = insertCharAt(word, first, j); permutations.add(s); } } return permutations; } public static String insertCharAt(String word, char c, int i) { String start = word.substring(0, i); String end = word.substring(i); return start + c + end; } public static void main(String[] args) { ArrayList<String> list = getPerms("abcde"); System.out.println("There are " + list.size() + " permutations."); for (String s : list) { System.out.println(s); } } } This is what I have thought untill now : At any function call , the number of words available is (n-1) ; assuming we are at a place where remainder is of length (n-1). Now to insert the nth element in all possible places for all of these (n-1) words takes (n-1)*(n-1) time.
so across the execution , it should be (n-1)^2+(n-2)^2+(n-3)^2+....2^2+1^2 operations, which I don't think is n!.
What did I miss here?