Home > OS >  Failing to debug index out of range error in recursive code of Finding Permutation
Failing to debug index out of range error in recursive code of Finding Permutation

Time:11-03

This is the leetcode questions on permutation Runtime Error, "List Index Out of Range" basically I getting the first permutation only

This is how my rough recursive tree looks like:

Recursive Tree

Kindly help me to mitigate this issue!!

This is how I have resolved it:

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        output = []
        backtrack(nums, [], output)
        return output
    
def backtrack(nums, current, output):
    if(len(nums) == 0):
        output.append(current)
        return
    else:
        for i in range(len(nums)):
            ip1 = nums[:i]   nums[i 1:]
            op1 = current   [nums[i]]
            backtrack(ip1, op1, output)

CodePudding user response:

The main issue is this:

ip1.remove(ip1[i])

While you're iterating over the list, you're also removing elements. As a result, after a few iterations, the number of elements in the list becomes lower than the current value of i and you get the index error.

As a simple workaround, you could maintain the elements in a separate temporary list, where you do the removals.

  • Related