How do we find the time complexity of below program? For the below program should the time complexity be O(N) or O(N*M) or O(N*M*M)?
Take-1: O(N)
- to scan N elements in the input array
Take-2: O(N*M)
- N is number of elements in the input array
- M is length of the longest email address in the list for
splitandfind
Take-3: O(N*M*M)
- N is number of elements in the input array
- first M is length of the longest email address until @ in the list for
split - second M is length of the longest email address in the list for
find
input_mails = ["[email protected]","[email protected]"]
for email in input_mails:
first_part, second_part = email.split("@")
position = email.find(".")
print(first_part)
The time complexity of the given program will be
N*2M~O(N * M)where:Here's how the operations contribute to the time complexity:
Nelements in the input array:O(N)@:O(M), as splitting depends on the length of the longest email address..:O(M), as finding the dot also depends on the length of the longest email address. Now, one point to note here isfind()has the worst case time complexity ofO(p*q)wherepbeing the length of the longer string,q, the shorter string you search for. But since you mentioned you need to find dot(.) soqbecomes 1 and for the context of your code it becomesO(M).References and further reading:
str.find()in pythonstr.find()