You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Your solution for the oranges rotting problem is correct and efficient in terms of worst-case time and space complexity. Well done on implementing the BFS approach correctly. However, there are a few points to improve:
Early Termination: Inside the inner loop when you process a neighbor, you can check if freshOranges becomes zero and return time immediately (without waiting for the entire level to process and without having to do another minute). This would make your solution more efficient in practice. For example, in the reference solution, they check inside the inner loop and return as soon as fresh becomes zero.
Space Complexity Comment: Your comment at the top says "SC - O(n)" but the space complexity of the BFS queue can be up to O(m*n) in the worst case. Please correct the comment to avoid confusion.
Variable Naming: Your variable names are generally good, but consider using more descriptive names like row and col instead of r and c for better readability.
Minute Counting: Your method of counting minutes by incrementing at the start of the while loop and then subtracting one at the end is correct, but it might be slightly unintuitive. Alternatively, you can initialize time to 0 and then after processing each level, increment time. Then you can break early when fresh becomes zero and return the current time. However, your current approach is acceptable.
Here is a slightly modified version that includes early termination:
public int orangesRotting(int[][] grid) {
int freshOranges = 0;
Queue<int[]> q = new LinkedList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.