_Satoru_'s blog

By _Satoru_, history, 2 years ago, In English

You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values: 0 represents an empty cell, 1 represents an obstacle that may be removed. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m — 1, n — 1). Constraints: 1 <= m, n <= 1e5 , 2 <= m * n <= 1e5

Problem Link: https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/

My Code

The solution is just a BFS where you push a neighbor of the current cell being processed if it can be reached after removal of lesser number of obstacles. Due to this a cell maybe pushed multiple times to the queue. I am not able to convince myself that the time complexity is O(nm) which it should be as per the constraints of the problem. How can we prove that each cell will be updated constant times?

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
2 years ago, # |
  Vote: I like it +6 Vote: I do not like it

Auto comment: topic has been updated by _Satoru_ (previous revision, new revision, compare).

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by _Satoru_ (previous revision, new revision, compare).

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You can try the worst case.The time complexity of your code is at least $$$O(nm)$$$

  • »
    »
    2 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    What will be the upper bound? It should be O(nm(n+m)) according to me but in that case the above code shouldn't be accepted but it does get accepted.

»
2 years ago, # |
  Vote: I like it +11 Vote: I do not like it

The test cases are weak. If you try it on a test with n=2, m=4k+1 that looks like

0100

0001

repeated k times with a column of 2 0s at the end, your code would be very slow.