ProgrammingModerate
A matrix of n x n values is read and the program needs the sum of all cells above the main diagonal. What is the cost, and is it correct to loop with j from i + 1?
- A. O(n^2) time, and looping with j from i + 1 visits each cell above the diagonal exactly once
- B. O(n) time, since only the diagonal matters
- C. O(n^3) time, since the loop is nested twice
- D. O(n^2) time, but cells on the diagonal are counted twice
Correct answer: A. O(n^2) time, and looping with j from i + 1 visits each cell above the diagonal exactly once
There are about n^2 / 2 cells above the diagonal, all visited once with j starting at i + 1. Cells on the diagonal are never included.
More C Programming questions
- For a 2D prefix sum with P[i][j] = sum of the first i rows and j columns, what is the cost of building it for an n x n grid?
- int grid[4][4] is filled by grid[i][j] = i j. What is grid[3][2]?
- For the grid [[1, 2, 3], [4, 5, 6]], what is the sum of the column 2 values (the third column, 0-based index 2)?
- In row-major order, the cell a[i][j] of a matrix with C columns sits at which flat index?
- A matrix multiplication of a 3 x 4 matrix by a 4 x 2 matrix produces a result of what size?
- How many scalar multiplications does the naive method use for a 3 x 4 times 4 x 2 product?