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)
Take-2: O(N*M)
split
and find
Take-3: O(N*M*M)
split
find
input_mails = ["abc@gmail.com","xyz@gmail.com"]
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:
N: number of elements in the input array (input_mails)
M: length of the longest email address in the list
Here's how the operations contribute to the time complexity:
N
elements 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 is find()
has the worst case time complexity of O(p*q)
where p
being the length of the longer string, q
, the shorter string you search for. But since you mentioned you need to find dot(.
) so q
becomes 1 and for the context of your code it becomes O(M)
.