Time Complexity of Recursive Algorithms

Keywords: MySQL Database Linux

Recursion algorithm should be familiar, in fact, the first encounter of recursion should be in mathematics class, similar to f(x)=f(x-1)+f(x+1), f(1)=1, f(2)=4, f(3)=3, you should have seen many mathematical problems, in fact, the idea is hierarchical recursion, and ultimately the target value is expressed in f(1), f(2), f(3).

We used MySQL database to record data. There are four columns in the table field: id, index_name, pid, is_directory, index_name to record the name of the file or file, PID to record its parent id, is_directory to mark whether it is a file or a folder.

After the records are saved, the problem of data extraction is involved. The target data structure that we need at the front end is as follows:

[{"id":1,"name":"./"},{"id":2,"name":"./1.txt"},
{"id":3,"name":"./dir1/"},
{"id":4,"name":"./dir1/2.txt"},...]

It's a bit like the tree command of a linux system.

The first version of the code is as follows:

tree = []
def getTree(pid):
              return
for index in childIndexes:
 if len(tree) == 0:
   if index.is_directory==1                            tree.append(
{'id':index.id,'name':'./'+index.index_name+'/'})                     
getTree(index.id)
                     else:                            
tree.append(
{'id':index.id,'name':'/'+index.index_name})
              else: 
                    for item in tree:  
if item['id'] == index.id
                                   if item.is_directory==1:                                          tree.append({'id':index.id,'name': 
item['name']+index.index_name+'/'})    
                               else:  
                                        tree.append
(
{'id':index.id,'name':item['name']+index.index_name
}
)

Looking at the time complexity of this algorithm, the time complexity of the first layer is n, the time complexity of the second layer is n, the time complexity of the inner layer is O (n^2), and the time complexity of the last layer is O (2^n*n^2). This algorithm can be seen to be very rough, if the recursion depth is 100, and finally persistent. Efficiency can make your scalp numb. Next, let's consider how to optimize.

Second Edition Code:

tree = []
def getTree(pid,path='./'):
              return
       for index in childIndexes:
             if len(tree) == 0: 
                    if index.is_directory==1                            tree.append({'id':index.id,
'name':path+index.index_name+'/'}) 
                           getTree(index.id, 
path+index.index_name+'/')
                    else:
                           tree.append({'id':index.id,
'name':path+index.index_name}) 
             else: 
                    if item.is_directory==1:                            tree.append({'id':index.id,
'name':path+index.index_name+'/'})
                     else: 
                           tree.append({'id':index.id,
'name':path+index.index_name})

Let's save each path with a variable, and this time we'll look at the time complexity. The first traversal time complexity is O(n), and the last time complexity is O(2^n*n), which is not ideal, at least better than the first one.

Look at a common topic in an interview, Fibolacci series, n=1,1,3,5,8,13.... What's the number n?

The first thing that comes to mind is the recursive approach:

def fibSquence(n):     
  if n in (1,2):       
   return 
   fibSquence(n-1)+ fibSquence(n-2)

The time complexity of this algorithm is O(2^n), which can be understood by the number of calls. Let's consider how to optimize, for example, to find n=3, we need to first find n=2,n=1, but initially n=1,n=2 has been solved, two more steps of repeated calculation.

Here is the optimized code:

fibMap = {1:1,2:2}
def fibSquence(n):
       else:
        result = fibSquence(n-1)+ fibSquence(n-2)              fibMap.update({n:result})
              return result

We use map to store the median value. The map is based on hash and the time complexity is O(1), so the time complexity of this algorithm is O(n).

But in fact, this problem does not need to be solved recursively.

fibMap = {1:1,2:2}
def fibSquence(n):
       else:
              for i in range(3,n+1): 
                    fibMap.update({i:fibMap[i-1]+fibMap[i-2]})
              return fibMap[n]

In this way, we can get the target value by only one traversal.

The optimization of recursive algorithm is probably to avoid repeated operations and save the status of Zhongjin for next use. From the structural point of view, it is to transform the time complexity into the space complexity to solve it. The efficiency of recursive algorithm is very low, so I can avoid recursion as much as possible without recursion. Of course, we should also deal with specific problems, such as starting to mention the problems I encountered in my project, and I really can't think of any better way to solve them without recursion.

Author: Yang Yi

Source: Yixin Institute of Technology

Posted by weknowtheworld on Sun, 01 Sep 2019 23:17:19 -0700