Mastering Matrices in Javascript: A guide to Multidimensional Arrays (Part 1)

Giulia Elizabeth
3 min readFeb 22, 2021

--

When first solving problems with multidimensional arrays it can be a little intimidating. In this article we will examine some easy problems to understand some patterns, and move along to more difficult ones. You can follow-along and test your understanding by completing the leetcode problems mentioned. Good luck!

The first problem we will be looking at is Leetcode 1572. In this problem you are given a Matrix and asked to find the sum of the two diagonal.

In our iteration we are increasing i and decreasing j by one each time. Therefore arr[i][i] will give us D1 and arr[i][j] will give us D2.

Step by Step:

  1. Set a variable sum=0 to track the sum of the two diagonals
  2. Set a variable j which will be used to find the D2 in our matrix. The value will be equal to the index of the last item of our rows j= arr[0].length-1 (in this case 3). This will be decremented by our iteration in the next step.
  3. Now we will iterate through the matrix adding a third variable i=0 which will be used to find both diagonals D1= arr[i][j], and D2=arr[i][i]. In our iteration we will increase i each time, and j will decrease each time.
  4. We will add the condition if(i !== j) to prevent from counting the center twice (in the case of a (3 by 3 array).
  5. Now every-time we iterate through we will move both diagonals towards the bottom (left or right) of the array, and add the value to the sum.
  6. This will stop once i = 4 and is no longer < arr.length

This can also be done with a forEach loop as you can see below.

leetcode 1572

The next problem we will be looking at is Leetcode 1380. Here we are asked to return the number that is both the minimum in its row and maximum in its column.

Step by Step:

  1. Iterate though the matrix.
  2. Set variable min= Infinity so we have a starting point (to compare min to in the next line).
  3. Then we will equal min to the smallest value for that row (…matrix[i]). In the first iteration the number will be compared to infinity (Math.min(min, )) since it will be smaller it will update the value of min.
  4. Next we will find the index of the min value, which we will use as the column (minIndex = matrix[i].indexOf(min))
  5. After finding the min of the row we will use the index (as the column) in our while loop to find the max value in that column, by comparing each number in the column to the previous max value.
  6. At the end of each while loop iteration we will see if the minimum value of that row is equal to the max value of that column min === max. If so we got our column!

--

--

No responses yet