I have the following code that checks if the sum of three positions in an array v
of integers is equal to a given number x
.
def triplet(array, sum):
array_size = len(array) # 1
for i in range( 0, array_size-2):
for j in range(i + 1, array_size-1):
for k in range(j + 1, array_size):
if array[i] + array[j] + array[k] == sum:
return True # 1
return False # 1
What would be the time complexity of the nested loops inside the code as well as the worst-case complexity? As far as I understand, the worst-case complexity for the whole function is O(n^3) since the function needs to perform a linear time operation for each value in the input data. Is that correct?
I have commented out the lines with the constant complexity as # 1
. What would be the time complexity for other individual for
loops as well as for the if
condition in the last for
loop?
The time complexity is O(n^3).
To calculate it you have to add up how many machine instructions it will execute as a function of the size of its input, and then simplify the expression to the largest (when N is very large) term and can include any simplifying constant factor.
For reference and deeper explanation check out->
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.