leetcode/1260: rotate_right#386
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements the solution for LeetCode 1260, "Shift 2D Grid", in Rust. The feedback suggests adding a guard clause to handle empty grids safely, preventing potential panics from division by zero or unwrapping empty options. Additionally, it recommends using chunks_exact to group the flattened vector into rows, which is a more idiomatic and efficient approach than using nested loops with pre-allocated vectors.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| let n = grid.len(); | ||
| let m = grid.first().map(|row| row.len()).unwrap(); | ||
| let mut elements: Vec<i32> = grid.into_iter().flatten().collect(); | ||
| let mut shifted = vec![vec![0; m]; n]; | ||
| elements.rotate_right(k as usize % (m * n)); | ||
| for r in 0..n { | ||
| for c in 0..m { | ||
| shifted[r][c] = elements[r * m + c]; | ||
| } | ||
| } | ||
| shifted |
There was a problem hiding this comment.
The current implementation has a few areas for improvement:
- Safety: If
gridis empty or contains empty rows, calling.unwrap()ongrid.first()or performing modulo division bym * n(which would be0) will cause a panic. Adding a guard clause makes the function robust. - Efficiency & Idiomatic Rust: Instead of pre-allocating
shiftedwith zeros and manually copying elements using nested loops, you can usechunks_exactto group the flat vector into rows and collect them directly. This avoids double-initialization and is much more idiomatic.
if grid.is_empty() || grid[0].is_empty() {
return grid;
}
let m = grid[0].len();
let mut elements: Vec<i32> = grid.into_iter().flatten().collect();
elements.rotate_right(k as usize % elements.len());
elements.chunks_exact(m).map(|chunk| chunk.to_vec()).collect()
No description provided.