Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

TIMES OF RISING Latest Articles

How do you set a matrix to zero?

The jitters and nervousness of a coding interview is more than real! 

No matter how much you prepare for a coding interview, some kind of uncertainty always exists! 

From array questions to the longest palindromic substring to binary tree to graph problem to duplicates in array, you can expect several types of questions in a coding interview. 

One such topic that holds great importance in a coding interview is set matrix zeroes

A zero matrix is one whose all the elements are equal to 0. In a set matrix zero, the elements of a given matrix are 0 and you have to find it. 

To keep the importance of this topic in consideration, we have curated this blog post. 

Read on and fill your knowledge bank! 

Set matrix zero 

For a given set of matrices with the value 0, you may be required to find the elements. Note that no extra space would be needed in order to perform the operations.

Consider the problem statement;

A matrix is given. If the elements in that matrix are 0, you need to set an entire column and rows to 0 by returning the matrix. 

Let’s take an example;

Matrix is [ 1, 1, 1 ] [ 1, 0, 1] [ 1, 1, 1 ]

The output would be [ 1, 0, 1] [ 0, 0, 0 ] [ 1, 0, 1 ] 

Explanation: As the matrix [ 2, 2] = 0. You can set the 2nd column and the 2nd row as the 0. 

Approaches to follow

Brute force approach 

While using the brute force approach, the common mistake that you may commit is to traverse the matrix for any given 0. You can update all the values in the rows or columns as 0. The solutions in this case may seem quite easy but it can lead to some of the wrong solutions.

The correct solution idea to follow:

One way would be to create the auxiliary matrix which is of the same size and gets filled with 1s. You can make the necessary changes in this auxiliary matrix to copy it with the original matrix in the end. 

You may need to search for the zeroes in an original matrix in order to update all the rows or columns in the auxiliary matrix. 

Follow these steps:

  • At first, you need to create the temporary matrix of the size M *N to initialise it at all the needed places with a 1 
  • Then scan an original matrix. In case, the A [i] [j] == 0, you can set at all the positions of the row i and the col 1 with a 0 in the new matrix
  • Copy all the desired elements from your temporary matrix into the original matrix

Simply in a brute force approach, you may need to identify all the zeroes. For every zero detected, you can change all the elements except that zero in a row or a column to get the – 1. 

The complexity analysis 

For all the cells, you may need to traverse the rows or columns with the total of N*M cells. 

The time complexity in this case would be O [N *M ( N +M )] 

However, the space complexity will be O [N / M]  to store the given auxiliary matrix. 

Using the hash tables 

Another approach to follow for finding the set matrix zeroes is by using the hash tables. Here, you are not using the auxiliary matrix to store the rows or columns that need to be updated. 

You can create the hash tables for all the desired columns and rows to later update them as true. This is the signal for us to update any particular row or column with its value as 0. 

The solution steps to follow in this case are:

  • Create any two hash table rows and columns respectively. Of the size M and N
  • Now, you can initialise all the given values of rows [] and col[] to consider it false 
  • Now you can iterate over a matrix for the A [i] [j] == 0 with the set row [i] = true col[j] as true 
  • After you complete step 3, iterate again through the matrix A for the given A [i] [j] , if you get the row [i] and the col [j] would be true, update the A [i] [j] to be 0. 

The time complexity, in this case, would be as such where you need to create or fill the values of two given hash tables + traverse the matrix + update the given matrix 

The space complexity in this case would be the O [M + N] to store the hash tables. 

Using the in-place hashing 

You may need the extra space for storing rows and columns in a hash table.  In this case, we would be able to optimise the space in a way that will help you store the rows or columns in that particular matrix. 

Use the first row or the first matrix for storing the status of your rows and columns. The problem may occur in the case of the first row or matrix where you need to handle two variables.

The steps to follow in this case are:

  • Initialise the given first row or column as false and the two variables will store the status. 
  • You can use the first row or the first column to your hash in order to store the status of that row or column. 
  • Iterate over the whole matrix 
  • Now you can update the values for storing the matrix except in the case that the first row or the first column needs to be 0
  • Update the value of your first rows and first columns 

The time complexity in this case would be 

Checking the first row and columns + traversing or updating the matrix + updating the first row and column 

The space complexity in this case will be O [1] 

Wrapping Up 

From duplicates in arrays to string questions to binary tree questions, you may encounter several types of questions in a coding interview. 

In this blog, we explained the concept of set matrix zero. Keep this blog as your mentor and fill your knowledge base in the right direction. 

Happy learning!

Related Posts

You must login to add a comment.

Latest News & Updates

TIMES OF RISING Latest Articles

Top 7 Tax Preparation Services and Apps That Save You Money

Tax season can be stressful and costl ...

Best Online MBA Programs That Actually Pay Off in 2025

In today’s competitive business envir ...

How to File a Mesothelioma Claim: Legal Rights and Settlement Guide

Mesothelioma is one of the most devas ...

Best Auto Insurance Providers for Young Drivers (2025 Update)

Finding affordable auto insuranc ...

Top 5 Mortgage Refinance Options with Lowest Rates in 2025

Refinancing a mortgage can be a smart ...

How to Get Affordable Health Insurance as a Freelancer

Freelancing offers unparalleled freed ...

Best Credit Cards for Cashback & Rewards in 2025

In 2025, cashback and rewards credit ...

How to Consolidate Your Student Loans in 2025 (Step-by-Step Guide)

Consolidating your student loans in 2 ...

Top 10 Life Insurance Companies with Lowest Premiums in the USA

Discover the top 10 life insurance co ...

Best Small Business Loan Options in 2025: Rates, Terms, and How to Apply

Discover the best small business loan ...

The Future of Cyber Security: A Comprehensive Guide

Explore the future of cybersecurity i ...

How Web 3 Advertising is Transforming Digital Marketing?

How Web 3 Advertising is Transforming Digital Marketing?

Discover how Web 3.0 advertising is t ...

F&O trading in India: Essential insights for new and experienced investors

F&O trading in India has quickly ...

How to Earn Money from YouTube Shorts: Ultimate Guide

With the explosive growth of YouTube ...

The Importance of ESG Practices in the Bottled Water Sector

Discover the importance of ESG practi ...

Freelance Writing: A Comprehensive Guide

Freelance writing has rapidly become ...

17 Ways to Make Money Online Without Investment

In today’s digital world, makin ...

How to Choose the Right Digital Marketing Agency for Your Business

In today’s digital world, a sol ...

Expert Advice: How To Excel With A Banking And Finance Course

In today’s fast-paced world, a ...

Efficiency and Accuracy: How SpinBot’s Spell Checker Enhances Proofreading Processes

In today’s fast-paced digital e ...

Rewording vs. Paraphrasing: Understanding the Differences

In the world of writing, the terms &l ...

How to Buy Watches Online That Complement Your Every Outfit

Online shopping has changed our ways ...

Dreaming of a Getaway? How can a Travel Loan Take you there?

Dreaming of a Getaway? How can a Travel Loan Take you there?

Recently, the desire for national and ...

10 Essential Business Services to Boost Your Success

Running a successful business require ...

STEP-BY-STEP ALGORITHM FOR PREPARING WALLS FOR PAINTING

Painting a room may seem like a strai ...

Turning Waste into Resources: Managing Used Cooking Oil Disposal

The world is currently facing signifi ...

The Rise of Sustainable Fashion: A Guide to Ethical and Eco-Friendly Choices

The Growing Movement of Sustainable F ...

The Rise of Electric Vehicles: A Sustainable Future

Electric vehicles (EVs) have witnesse ...

Navigating the Digital Jungle: A Comprehensive Guide to Cyber Security

In today’s digital age, our liv ...

Revolutionizing Healthcare: The Impact of AI on Patient Care

The Future of AI in Healthcare: A Dee ...

Key Factors to Consider When Choosing a Digital Marketing Agency

Key Factors to Consider When Choosing a Digital Marketing Agency

In today’s digital age, a stron ...

AI for Content Writers: Revolutionizing the Content Creation Industry

The rise of artificial intelligence ( ...

Generative AI: A Double-Edged Sword

The advent of generative artificial i ...

The Future of Work: AI’s Impact on the Job Market

The rapid advancement of artificial i ...

Why Rose Gold Watches for Women a Must-Have Accessory

Why Rose Gold Watches for Women a Mus ...

AI Characters & The Future of Human-AI Collaboration

There was a time when the idea of hum ...

Exploring the Top Demat Account Apps for Maximum Efficiency

Managing investments has become easie ...

Top Social Media Strategies for Lead Generation

Lead generation

Flyfish Review – The Ultimate Solution to the Global Business Complications

Running a business is indeed a techni ...

Why do I need Scrum Product Owner Certification?

Executing complex and large projects ...

Things to Remember Before Hiring a Building Facade Cleaning Company in Dubai

Maintaining the exterior of your buil ...

Finding the Best Exhibition Stand Manufacture Company in Dubai

Dubai, a global hub for business and ...

Corporate Gifting in Dubai: The Key to Building Strong Business Relationships

Corporate Gifting in Dubai: The Key to Building Strong Business Relationships

Corporate gifting Dubai is more than ...

Elevating Business Success: The Impact of Business Analysis Consultancy

In today’s competitive and rapi ...

Waterproofing Basement Walls from the Inside in Royal Oak: A Comprehensive Guide

In Royal Oak, Michigan, where basemen ...

Shoes For Athletes: How To Identify Performance-Driven Footwear For Sports And Fitness

Having the right footwear is one of t ...

How to Manage a Social Media Marketing Campaign Properly?

Managing a social media marketing cam ...

The Art of Abhinaya: Know the Importance of Emotion and Expression in Indian Classical Dances

Diversity of India India is a country ...

Getting Started with Online Forex Trading: Essential Steps

Online Forex trading has become incre ...

Latest 2024 Guide To Selling Your Business Online: Tips And Strategies

In today’s booming eCommerce la ...

E-commerce Accounting and Sales Tax: Know How To Ensure The Compliance With The Government Rules

E-commerce has revolutionized the way ...

Private Jet Prices: How Much Does it Cost to Fly in Style?

Private jets are the ultimate luxury ...

The Benefits Of Having A Firm That Is Registered In Your Name

You’re not alone! Millions of c ...

Why is it okay to take small loans?

When you’re buying a house, the ...

How Rostering Software Can Help Your Business

Small to medium-sized businesses may ...

Benefits of attending a CX event

There are many benefits to attending ...

Investment Advisors and Their Services: Property and Real Estate

With the right investment advisor, on ...

Fertility Specialist: It’s Always Early Enough to Consult

Infertility is a common condition tha ...