What is the time complexity of this problem?

The following pseudo-code represents an algorithm that takes as input an array of elements that can contain either positive integers or strings. In other words, the input could look like this [42, 'a', 1, 'hello', 3] .

The algorithm outputs an array with the following properties: elements in the output alternate between being a string and being an integer, and each element is less than or equal to the previous element of the same type (except for the elements at position 1 and 2, which are the largest of their respective types). In computer science, it is possible to sort strings ('b' > 'a', for example). This output will contain more elements than the input if the input does not have the same number of integers and strings.

What is the runtime of this algorithm?

For this example, assume that the sorting algorithm Reverse_Cheating_Sort(A) is a constant O ( 1 ) O(1) operation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Crazy_Sort(A):
    strings = []
    integers = []
    num_strings = 0
    num_integers = 0
    for i = 1 to i = A.length:
        if type(A[i]) == 'string':
            num_strings = num_strings + 1
            strings.push(A[i])
        else:
            num_integers = num_integers + 1
            integers.push(A[i])
    if num_strings > num_integers:
        for i = 1 to i = num_strings - num_integers:
            integers.push(1)
    else if num_integers > num_strings:
        for i = 1 to i = num_integers - num_strings:
            strings.push('a')
    result = []
    strings = Reverse_Cheating_Sort(strings)
    integers = Reverse_Cheating_Sort(integers)
    for i = 1 to i = strings.length:
        result.push(strings[0])
        result.push(integers[0])
    return result

O ( 1 ) O(1) O ( n ) O(n) O ( 2 n ) O(2n) O ( n 2 ) O(n^2)

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Thanh Nguyen
Dec 28, 2017

This algorithm has three main steps: 1. Iterate through the input array to partition the array into 2 arrays: one stores strings, and the other stores integers. 2. Ensure they have the same size by add dummy elements to the shorter one. This is for the alternation. 3. Sort both of them using the Reverse Cheating Sort function and alternate elements in the sorted arrays to get the ouput.

Time complexity is O(n) for n is the size of the input array due to the three 'for' loop and the magical O(1) reverse routine. O(2n) is basically of the same order as O(n), but O(n) is more accurate, asymptotically.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...