Search code examples
python-3.xoptimizationruntime-errordynamic-arrays

Dynamic Array Runtime Error - code working but not for large input values | How to resolve?


This is the code I wrote and seems like it's working but when I checked on the Hackerrank for testing with the huge test cases - it's giving me a runtime error. How can I optimize this code?

def dynamicArray(n, queries):
    lastAnswer = 0
    seq = []
    result = []
    for k in range(0, n):
        seq.append([])

    for i in queries:
        N_querytype = i[0] #it can be either 1 or 2
        x = i[1]
        y = i[2]
        index = (x ^ lastAnswer) % n
        if(N_querytype == 1):
            seq[index].append(y)
        elif(N_querytype == 2):
            lastAnswer = seq[index][y]
            result.append(lastAnswer)
    return result

This is the test-case for which it is not running. Is there something I am missing?


Solution

  • Your answer was close but you misunderstood what to do in query 2

    Find the value of element y % size in seq (where size is the size of seq) and assign it to

    So using index you get the sequence which will be a list, but you are then asked to find the value in the list whic his indexed at position y % size where size = len(seq[index])

    def dynamicArray(n, queries):
        lastAnswer = 0
        seq = []
        result = []
        for k in range(0, n):
            seq.append([])
    
        for i in queries:
            N_querytype = i[0] #it can be either 1 or 2
            x = i[1]
            y = i[2]
            index = (x ^ lastAnswer) % n
            print("#", index, y)
            if(N_querytype == 1):
                seq[index].append(y)
            elif(N_querytype == 2):
                size = len(seq[index])   #Calculate the size of the sequnce at this index
                lastAnswer = seq[index][y % size] #look up the value in this sequence at index y % size
                result.append(lastAnswer)
        return result