I was solving an algorithm problem which has to do with combinations from AlgorithmFridays
I defined a function combinate
combinate(combos, string):
new_combo = []
for combo in combos:
for char in string:
new_combo.append(combo + char)
return new_combo
I knew the combinate function will run in O(n^2) time complexity (quadratic time).
In other to ensure my solution is accepted in the competition, I knew I had to optimize the combinate function. This is because the function would be called within a for loop which would lead to O(n^3) time complexity.
I later came up with what I think is an optimization. Here is the new combinate function definition:
combinate(combos, string):
new_combo = []
repeater = len(string)
index_c = 0
index_d = 0
while index_c < len(combos):
if index_d == repeater:
index_d = 0
index_c += 1
continue
new_combos.append(combos[index_c] + string[index_d])
index_d += 1
return new_combo
I noticed, that I could use a while loop and extra variables to achieve the same result as using a nested for loop when I found out, that there was a pattern.
Question
Since the while loop relies on index_c to terminate and index_c increases by 1 on every 3 iterations.
Does it have any advantage over the nested loop version in terms of speed???