Reshape a Pixel Buffer Into New Dimensions in Row-Major Order

Last updated: November 29, 2026

Quick Overview

Given an m x n pixel matrix and target dimensions r x c, return the matrix reshaped by reading pixels in row-major order into the new shape, or the original matrix if the total pixel count does not match.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given an m x n pixel matrix and target dimensions r x c, return the matrix reshaped by reading pixels in row-major order into the new shape, or the original matrix if the total pixel count does not match.

A quick Google phone screen warm-up similar to a NumPy reshape on image tensors. The interviewer checks index mapping, the size validation, and whether you can do it in a single pass without building an intermediate flat list.

What the Interviewer Expects
  • Validates m * n == r * c
  • Maps each source index to a destination with divmod
  • Builds the output in one pass
  • Returns the original when sizes mismatch
  • States O(mn) time
Key Topics to Cover
Index Mapping
Matrix Reshape
Row-Major Layout
Validation
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Support column-major (Fortran) order as an option.
  • Return a lazy view that reshapes without copying.
  • Support a -1 dimension that is inferred from the total size.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: mat m x n, integers r, c.
  • If m*n != r*c, return mat unchanged.
  • Otherwise return an r x c matrix holding the same values in row-major order....
High-Level Design

The flat index of (i, j) in the source is i*n + j. The same flat index lands at divmod(k, c) in the destination. Iterate the source once and write each value into its destination slot. This avoi...


Submit Your Answer
Markdown supported