ZigZag traversal
This is one of the question from algoexpert and this is my solution involving math
def zigzagTraversal(arr):
out = []
test = 1
out.append(arr[0][0])
while test <= len(arr)+len(arr[0]):
for j in range(len(arr[0])):
for i in range(len(arr)):
if test % 2 == 1:
if i + j == test:
# print(arr[i][j])
out.append(arr[i][j])
else:
if i + j == test:
out.append(arr[j][i])
test += 1
return out
print(zigzagTraversal([[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16]]))
Let
N=len(arr), M=len(arr[0]). This code hasO(NM^2+N^2M)complexity (orO(N^3)for square input matrix). Here's why: outer loop (while) is fully equivalent toforloop (because you incrementtestat the end and never change it elsewhere) and will be executedN+Mtimes. Then you enter the second loop which is executed exactlyNtimes. Then inner loop -Mtimes. Inner loop will be repeated for each step of middle loop, the same with outer. So we have to multiply all this counts together. All inner operations are not atomic, of course, but for small data will beO(1)on average. If your input is large, I suggest pre-allocatingout(creating it asout = [None for _ in range(N*M)]) to avoid costs of its growth and keeping current first free index as additional variable.