Time complexity of traversing a 2d array

Again, determining time complexity is based on the algorithm not the input. It's about how many times it processes over N. x = [ [1, 2], [3, 4], [5, 6] ] for i in range(len(x)): for j in range(len(x[i])): print(x[i][j]) I changed the above example with increasing indices. x[0] contains length of 2, x[1] contains length of 2, x[2] contains length of 2. This represents a 3 x 2 matrix. In the first iteration it will loop 3 times and in the inner loop for each outer loop, loop 2 times for a total of 6 iterations. The input size though is an array of length 3. N = 3. Consider this example: x = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] for i in range(len(x)): for j in range(len(x[i])): print(x[i][j]) This represents a 3x3 matrix which will be 9 iterations with an input length of 3. Thus, the worst-time complexity is O(N2).

What you interpret to be N is thus important because if you define N to be 9 in the previous example, you will conclude the time-complexity is O(N), but that's not how time-complexity analysis works. You can't just interpret N to be whatever you want it to be and say its of a lower complexity. N does not represent the total elements. N is the size of the outer array and as you increase that outer size, the worst-case is O(N2 ) and average case is O(N).

/r/learnprogramming Thread Parent