FastPrepMatrix Multiplication

Matrix Multiplication

eBay logoeBay● EasyFULLTIMEONSITE INTERVIEW

Problem statement

You are given two integer matrices a and b. Matrix a has m rows and k columns, and matrix b has k rows and n columns.

Return their product c = a × b. It has m rows and n columns, and each entry is the dot product of one row of a and one column of b:

c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + ... + a[i][k - 1] * b[k - 1][j]

Function

matrixMultiply(a: int[][], b: int[][]) → int[][]

Examples

Example 1

a = [[1,2,3],[4,5,6]]b = [[7,8],[9,10],[11,12]]return = [[58,64],[139,154]]

a is 2 × 3 and b is 3 × 2, so the result is 2 × 2.

  • c[0][0] = 1*7 + 2*9 + 3*11 = 58
  • c[0][1] = 1*8 + 2*10 + 3*12 = 64
  • c[1][0] = 4*7 + 5*9 + 6*11 = 139
  • c[1][1] = 4*8 + 5*10 + 6*12 = 154

Example 2

a = [[1,2],[3,4]]b = [[0,1],[1,0]]return = [[2,1],[4,3]]

Multiplying by b on the right swaps the two columns of a. For example, c[0][0] = 1*0 + 2*1 = 2 and c[0][1] = 1*1 + 2*0 = 1.

Example 3

a = [[1],[-2]]b = [[3,0,4]]return = [[3,0,4],[-6,0,-8]]

Here k = 1, so each entry is a single product: c[i][j] = a[i][0] * b[0][j]. The first row is 1 times [3,0,4], and the second row is -2 times [3,0,4], which is [-6,0,-8].

Constraints

  • 1 <= a.length <= 40 (so m <= 40)
  • 1 <= b.length <= 100 (so k <= 100)
  • 1 <= a[i].length <= 100
  • 1 <= b[i].length <= 40 (so n <= 40)
  • All rows of a have the same length, and all rows of b have the same length.
  • The number of columns of a equals the number of rows of b: a[0].length == b.length.
  • -1000 <= a[i][j], b[i][j] <= 1000
  • Every entry of the result is between -10^8 and 10^8, so it fits in a 32-bit integer.

More eBay problems

See eBay hiring insights
Saved
public int[][] matrixMultiply(int[][] a, int[][] b) {
    // Write your code here.
}
Checking account…