Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse String In Place and Matrix Rotation

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Reverse String In Place and Matrix Rotation. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Myntra's catalog and personalization systems frequently transform ordered data. Implement two related in-place operations: reverse a mutable character sequence without allocating another sequence, and rotate a matrix 90 degrees clockwise.

Requirements

  1. Reverse chars in place. The input is a list of single-character strings, representing a mutable string buffer.
  2. Rotate a square matrix 90 degrees clockwise in place using transpose followed by row reversal.
  3. Adapt the rotation for rectangular matrices. A rectangular rotation changes the matrix dimensions, so return a newly shaped matrix for this case and explain why strict in-place rotation is not possible with Python's nested-list representation.
  4. Return the final character list and matrix from one function so the transformations can be verified directly.

Formal Specification

Implement reverse_and_rotate(chars, matrix), where chars is list[str] and matrix is a non-empty rectangular list[list[int]]. Return a dictionary with keys chars and matrix. The character list must be mutated in place. Square matrices must be mutated in place. For rectangular matrices, the returned matrix must contain the clockwise rotation.

Example 1

  • Input: chars = ['m', 'y', 'n', 't', 'r', 'a'], matrix = [[1, 2], [3, 4]]
  • Output: {'chars': ['a', 'r', 't', 'n', 'y', 'm'], 'matrix': [[3, 1], [4, 2]]}
  • Explanation: The characters are swapped from both ends, and the square matrix is transposed then each row is reversed.

Example 2

  • Input: chars = ['a', 'b', 'c'], matrix = [[1, 2, 3], [4, 5, 6]]
  • Output: {'chars': ['c', 'b', 'a'], 'matrix': [[4, 1], [5, 2], [6, 3]]}
  • Explanation: The rectangular result has three rows and two columns.

Constraints

  • 1 <= len(chars) <= 10^5
  • 1 <= rows, columns <= 200
  • Every matrix row has the same non-zero length
  • Matrix values are integers

Function Signature

def reverse_and_rotate(chars, matrix):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output