Time & Space Complexity - PERMUTATION
Time & Space Complexity - PERMUTATION
/**
* Recursive Backtracking using countMap.
*
* Time Complexity: O(N * N!). Number of permutations = P(N,N) = N!. Each
* permutation takes O(N) to construct
*
* T(n) = n*T(n-1) + O(n)
* T(n-1) = (n-1)*T(n-2) + O(n)
* ...
* T(2) = (2)*T(1) + O(n)
* T(1) = O(n)
*
* Above equations can be added together to get:
* T(n) = n (1 + n + n*(n-1) + ... + (n....2) + (n....1))
* = n (P(n,0) + P(n,1) + P(n,1) + ... + P(n,n-1) + P(n,n))
* = n * Floor(e*n!)
* = O(N * N!)
*
* Space Complexity: O(N). Recursion stack + countMap + tempList
*
* N = Length of input array.
*/
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
/**
* Iterative Solution
*
* The idea is to add the nth number in every possible position of each permutation
of the first n-1 numbers.
*
* Time Complexity: O(N * N!). Number of permutations = P(N,N) = N!. Each
permutation takes O(N) to construct
*
* T(n) = (x=2->n) ∑ (x-1)!*x(x+1)/2
* = (x=1->n-1) ∑ (x)!*x(x-1)/2
* = O(N * N!)
*
* Space Complexity: O((N-1) * (N-1)!) = O(N * N!). All permutations of the first
n-1 numbers.
*
* N = Length of input array.
*/
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
result.add(Arrays.asList(nums[0]));
return result;
}
}
Recursive Backtracking using visited array
/**
* Recursive Backtracking using visited array.
*
* Time Complexity: O(N * N! + NlogN). Number of permutations = P(N,N) = N!.
* Each permutation takes O(N) to construct
*
* T(n) = n*T(n-1) + O(n)
* T(n-1) = (n-1)*T(n-2) + O(n)
* ...
* T(2) = (2)*T(1) + O(n)
* T(1) = O(n)
*
* Above equations can be added together to get:
* T(n) = n (1 + n + n*(n-1) + ... + (n....2) + (n....1))
* = n (P(n,0) + P(n,1) + P(n,1) + ... + P(n,n-1) + P(n,n))
* = n * Floor(e*n!)
* = O(N * N!)
*
* Space Complexity: O(N). Recursion stack + visited array + Sorting + tempList
*
* N = Length of input array.
*/
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
Arrays.sort(nums);
permuteUniqueHelper(result, nums, new ArrayList<>(), new
boolean[nums.length]);
return result;
}