Skip to content
TheChatArchiveThe Chat Archive
MiniMaxminimax-m1· MiniMaxHugging Face LMArena Human Preference 140K

Given a matrix, rotate it 90 degrees clockwise in-place.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with grok-3-mini-beta’s answer.
  1. User

    Given a matrix, rotate it 90 degrees clockwise in-place.

  2. MiniMax Assistant

    To solve this problem, we need to rotate a given square matrix 90 degrees clockwise in-place. The solution involves two main steps: transposing the matrix and then reversing each row of the transposed matrix.

    Approach

    1. Transpose the Matrix: Transposing a matrix means swapping its rows with columns. For a square matrix, this can be done in-place by swapping elements across the diagonal.
    2. Reverse Each Row: After transposing the matrix, reversing each row will give the final rotated matrix.

    Solution Code

    def rotate(matrix):
        n = len(matrix)
        # Transpose the matrix
        for i in range(n):
            for j in range(i + 1, n):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        # Reverse each row
        for row in matrix:
            row.reverse()
    

    Explanation

    1. Transposing the Matrix:

      • The transpose of a matrix is obtained by swapping elements at positions (i, j) with (j, i) for all i < j. This ensures that we only swap each pair once, avoiding redundant swaps.
      • For example, in a 3x3 matrix, the element at (0, 1) swaps with the element at (1, 0), and so on.
    2. Reversing Each Row:

      • After transposing, each row of the matrix is reversed to achieve the 90-degree rotation. This step effectively moves elements from their transposed positions to their final rotated positions.

    This approach ensures that the matrix is rotated in-place with a time complexity of O(n²) and a space complexity of O(1), where n is the number of rows (and columns) in the square matrix. This is efficient as it meets the problem constraints and operates directly on the input matrix.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.