简体   繁体   中英

What is the time complexity and space complexity of a recursive algorithm with the || operator?

I have an algorithm that checks whether or not a game row can be solved. The game row is an array of positive integers, where the last element is 0. The game marker starts at index 0 and moves along the array the number of steps indicated by the integer it is positioned at.

For example, [1, 1, 0] returns true, while [1, 2, 0] returns false. The marker can also move left or right in order to solve the game. That is, [3, 3, 2, 2, 0] is solvable.

Algorithm recursiveSolvable(gameArray, index)
     if index = gameArray.length - 1     // the last element has been reached
          return true
     if index < 0 || index >= gameArray.length || arrayList.contains(index)
          return false
     arrayList.add(index)     // store visited indices to avoid infinite loop
     else
          // move towards the goal (last element) if possible
          // otherwise, trace back steps to find another way
          return recursiveSolvable(gameArray, index + gameArray[index])
                 || recursiveSolvable(gameArray, index - gameArray[index])

I have tried with a few examples of game rows and calculated the time complexity in the worst case:

[2, 0] has 2 recursive calls where the first one returns false, and the second one as well
[1, 1, 2, 0] has 5:
     go right || go left - false
        |
     go right || go left - false 
        |
     go right || go left - false (because index 0 has been visited)
        |
      false (then go left)

Other cases gave me numbers that I couldn't find the relation with the input size, but when I run the program with input size n = 100, the output is shown instantly, so I assume the time complexity is not O(2^n) (like binary recursion). I am more leaning towards O(n)...

As for the space complexity, I have no idea how to find it.

The run time is indeed more like O(n). This is because each index position is investigated only once (due to the test with the arrayList ).

The exact bound depends also on the data structure used for arrayList . Is it really a List or a HashSet ?

The space complexity is O(n) for the same reason. There can only be one incarnation of the recursive method for each index position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM