BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Computer vision31 of 35 in topic

787. Rotate a square image 90 degrees clockwise in place

MediumComputer vision Pro

On a device with tight memory, you may not be allowed to allocate a second copy of an image buffer. Rotating a camera frame then has to happen in place.

Write rotate_in_place(img). img is an n x n list of lists of pixel values. Rotate it 90 degrees clockwise by changing img itself, using only O(1) extra memory beyond a few variables. Return the same list object you were given.

An empty image [] is returned as it is.

Functiondef rotate_in_place(img)

Example 1

for img = [[1, 2], [3, 4]], rotate_in_place(img) returns [[3, 1], [4, 2]], and img itself now holds [[3, 1], [4, 2]].

Example 2

Input: img = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Constraints

  • 0 <= n <= 1,000
  • img is square
Hint 1

Write down where (i, j) goes after a clockwise turn.

Hint 2

A transpose plus a row reverse is the same map.

Hint 3

Mutate rows, do not replace them.

Common mistakes
  • Swapping every pair in the transpose, which undoes it.
  • Reversing columns instead of rows, which rotates counterclockwise.
  • Returning a new matrix instead of changing the input.
Understand the idea

In-place array work means rearranging data inside the buffer you already have. For rotation, transpose plus row reversal is the cleanest route: [[1, 2], [3, 4]] transposes to [[1, 3], [2, 4]], and reversing each row gives [[3, 1], [4, 2]]. The other classic way rotates four cells at a time in rings. On memory-limited hardware, in-place transforms avoid a second allocation the size of the frame.

Topics
Computer vision
Similar questions
  • Max pooling forward and backwardMedium
  • Detect edges with Sobel filters and a magnitude thresholdMedium
  • Unfold image patches with im2colMedium
  • Resize an image with bilinear interpolationMedium
All Computer vision problems
Report
787 / 903
Python 3solution.pyPython idle
1
2
3
4
def rotate_in_place(img):
# rotate img clockwise in place and return img
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS