What is the time complexity of this custom function?
Question:
Is it correct to say that the time complexity of the following code snippet is O(n^2)? My main doubt is whether I can consider triplets.append(sorted([array[i], array[j], twoSum - array[j]]))
as constant time since it does not depend on N and is always sorting an array of fixed size of length 3.
Function
def threeNumberSum(array, targetSum):
triplets = []
# O(n^2)
for i in range(len(array)):
twoSum = targetSum - array[i]
hashTable = {}
for j in range(i+1, len(array)):
hashTable[array[j]] = twoSum - array[j]
y = hashTable.get(twoSum - array[j])
if y != None and twoSum-array[j] != array[j]:
triplets.append(sorted([array[i], array[j], twoSum - array[j]])) # O(1)?
triplets.sort() # O(nlogn)
return triplets
Answers:
If the running time doesn’t grow as the N grows, then it is definitely O(1) in terms of Big O notation.
Sorting the array of fixed size is O(1) by definition.
Is it correct to say that the time complexity of the following code snippet is O(n^2)? My main doubt is whether I can consider triplets.append(sorted([array[i], array[j], twoSum - array[j]]))
as constant time since it does not depend on N and is always sorting an array of fixed size of length 3.
Function
def threeNumberSum(array, targetSum):
triplets = []
# O(n^2)
for i in range(len(array)):
twoSum = targetSum - array[i]
hashTable = {}
for j in range(i+1, len(array)):
hashTable[array[j]] = twoSum - array[j]
y = hashTable.get(twoSum - array[j])
if y != None and twoSum-array[j] != array[j]:
triplets.append(sorted([array[i], array[j], twoSum - array[j]])) # O(1)?
triplets.sort() # O(nlogn)
return triplets
If the running time doesn’t grow as the N grows, then it is definitely O(1) in terms of Big O notation.
Sorting the array of fixed size is O(1) by definition.