Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Problem Set 3

Questions to understand recursive complexity analysis

Question 1

In the previous lesson, we implemented merge sort where we divided the


array into two parts at each recursion step. Imagine you are asked to
implement merge sort by dividing the problem into three parts instead of
two. You can assume for simplicity that the input size will always be a
multiple of 3. Use a priority queue to merge sub-arrays in the combine step.

a- Provide implementation for the 3-way division merge sort.

b- Provide a generalized expression for the number of recursion levels.

c- Work out the time complexity for the 3-way merge sort.

d- Will implementing merge sort by dividing the problem into a greater


number of subproblems improve execution time?

Question 2

We implemented unoptimized code for generating permutations of a string.


The solution used extra space and also ran the main loop for the entire
length of the array on each invocation. Given the following optimized
solution, can you work out the time complexity?

1 class Demonstration {
2 public static void main( String args[] ) {
3 char[] array = new char[] { 'a', 'b', 'c', 'd' };
4 permutate(array, 0);
5 }
6
7 private static void swap(char[] str, int i, int j) {
8 char temp = str[i];
9 str[i](/learn)
= str[j];
10 str[j] = temp;
}
11 }
12
13 static void permutate(char[] str, int index) {
14
15 // base case
16 if (index == str.length) {
17 System.out.println(str);
18 return;
19 }
20
21 // regular case
22 for (int i = index; i < str.length; i++) {
23 swap(str, index, i);
24 permutate(str, index + 1);
25 swap(str, index, i);
26 }
27 }
28 }

Question 3

We are asked to implement a n-dimensional integer list. The constructor will


take in the parameter n and the class will expose two methods get(int n)
and put(int n) . If n equals 3, then we'll first create a list of 3 element, then
initialize each element of first list with another list of 3 elements and finally
initialize each element of the second list with a list of 3 elements. The get
and put functions act on the elements of the innermost list.

As an example, with n=3, we'll get a total of 27 elements. The get and put
methods should be able to specify index from 0 to 26.

a- Can you code the class?

b- What is the time complexity of initializing the list?

c- What is the time complexity of the get and put methods?

d- What is the space complexity?


(/learn)
←    Back Next    →
(/courses/big- (/courses/big-
o- MARK AS COMPLETED
o-

notation- notation-
for- for-
interviews- interviews-
Top Down and Bottom Up Approaches Solution Set 3
and- and-
beyond/YM08zoEwKWY) beyond/B8RJXPrVwVx)

Ask a Question
Report an
(https://discuss.educative.io/c/big-o-for-coding-interviews-and-beyond-c-h-
Issue
afzal/recursive-problem-set-3)

You might also like