简体   繁体   中英

If I use two variables to iterate through a 2D array is that still O(n^2) time complexity?

for (let i = 0; i < array.length; i += 1) {
  const row = array[i];
  for (let j = 0; j < row.length; j += 1) {
      const el = row[j];
  }
}

Would be a typical way to iterate through a 2D array nxn matrix and I'd consider that O(n^2) time complexity.

If I did this instead

let count = 0;
let i = 0;
let j = 0;
const n = arr.length;
const max = n * n;

while (count !== max) {
  const ele = arr[i][j];
  if (j === n - 1) {
    j = 0;
    i += 1;
  } else j += 1;
  count += 1;
}

Would it still be O(n^2)? Kind of a stupid question, I think the answer is yes, but I just want to double check. Obviously, the first method is much clearer, but then lower time complexity is good as well.

Given n = max(array.length, array[0].length) :

Yes - they are both O(n^2) . Even though it's one loop, the number of elements that the while loop goes through is the same as the number of elements that the 2 for loops go through.

In other words, with the for loop you're going through (approximately) n-sized chunks n times, and with the while loop you're going through an n^2-sized chunk once.

Well, it's not really O(n 2 ) in the first place.

Big-O tells you the worst-case performance of an algorithm by giving an idea of how its time of execution scales with the number of elements handled by the algorithm grows.

In the case of a 2-D matrix, while the matrix is, indeed, square (or, at least, rectangular), it's not really appropriate to use the length of the matrix as n here. Rather, you should be using the number of cells in the matrix ( i x j ).

A 2-D matrix is, effectively, an array of arrays and your algorithm is simply stepping through each cell once, making it O(n) in both cases. You could say that it's O( i x j ), but it's still a linear algorithm.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM