Time complexity of “Validate Subsequence” algorithm

  softwareengineering

Problem

Given two non-empty arrays of integers, write a function that determines whether the second array is a subsequence of the first one. A subsequence of an array is a set of numbers that aren’t necessarily adjacent in the array but that are in the same order as they appear in the array.

My Solution (in Python)

def isValidSubsequence(array, sequence):
    arrayCounter = -1
    arrayLen = len(array)

    for i in range(len(sequence)):
        while True:
            arrayCounter += 1

            if arrayCounter >= arrayLen:
                return False

            if array[arrayCounter] == sequence[i]:
                break

    return True

My question is about time complexity of this algorithm. It looks like quadratic because of 2 nested loops, but the second loop doesn’t run from start to finish every time. Instead it maintains counter which allows to continue from the previous location. So, can we say that this algorithm has linear time complexity?

LEAVE A COMMENT