Python solutions for some matrix problems

1. You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.

Jyothi
2 min readOct 2, 2024

A customer’s wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.

one-liner solution:

return max([sum(cust) for cust in accounts])

2. Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.

To flip an image horizontally means that each row of the image is reversed.

  • For example, flipping [1,1,0] horizontally results in [0,1,1].

To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.

  • For example, inverting [0,1,1] results in [1,0,0]

two liner solution :)

col_size = len(image[0])

return ( [ [image[i][col_size-j-1] ^ 1 for j in range(col_size)] for i in range(len(image))])

3. Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

3-line solution:)

res = sum (row[ii] + row[(-(ii+1))] for ii, row in enumerate(mat))

rr = len(mat)

res = res — mat[(rr)>>1][(rr)>>1] if (rr & 1) else res

4. Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

solution with O(m+n) :

col_ind = len(grid[0]) -1

tot_neg_nums = 0

# starting from top right and going down to bottom left

for row in grid:

while col_ind >=0 and row[col_ind] < 0:

col_ind-=1

tot_neg_nums += (len(grid[0]) — 1 — col_ind)

return tot_neg_nums

If we can have generator expression for the above logic, please share.

5. Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:

1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)

  • Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).

2. getValue(int row, int col)

  • Returns the current value of the coordinate (row,col) from the rectangle.

Solution:

Introducing Jyo Services — Your Go-To Partner for Tech Solutions

One-on-One Interview Preparation: Tailored coaching for freshers and professionals with up to 7 years of software development experience.

  • Patent Assistance: Comprehensive support for drafting, filing and maintaining patents in India.
  • College Projects: Professional guidance for Engineering students on academic projects.

DM me at: www.linkedin.com/in/jyothivs or jyos.v.s@gmail.com

--

--

No responses yet