BackhardGreedyRazorpayGoldman Sachs

Rotated Matrix Pivot Validator 7 Solution

Problem Statement

You are given an N × M integer matrix. Each row may have been independently rotated any number of positions to the left (a cyclic shift). Your task is to determine whether there exists a column index k (0‑based) such that, after applying an appropriate left rotation to every row, all elements in column k become identical. If such a column can be achieved, output the sum of all matrix elements (the sum does not change under row rotations). If it is impossible to make any column uniform, output -1.

Input format:

  • The first line contains two integers N and M – the number of rows and columns.
  • The next N lines each contain M space‑separated integers describing the matrix.

Output format:

  • A single integer: either the total sum of the matrix if a uniform column can be created, or -1 otherwise.

The solution must run in O(N · M) time and O(N · M) or less additional memory.

Example 1
Input
3 4 1 2 3 4 4 1 2 3 2 3 4 1
Output
30

Explanation: Row 1 needs no rotation. Row 2 is rotated left by 1 → [1 2 3 4]. Row 3 is rotated left by 3 → [1 2 3 4]. After these rotations column 0 contains the value 1 in every row, satisfying the condition. The sum of all elements is (1+2+3+4) + (4+1+2+3) + (2+3+4+1) = 30.

Example 2
Input
2 3 5 6 7 8 9 10
Output
-1

Explanation: The first row contains the set {5,6,7}, the second row contains {8,9,10}. There is no integer that appears in both rows, therefore no column can be made uniform regardless of rotations. The answer is -1.

Example 3
Input
2 2 3 3 3 3
Output
12

Explanation: Both rows already have the same value in every column. Column 0 (or column 1) already consists of identical elements (3, 3). No rotation is required. The total sum is 3+3+3+3 = 12.

Constraints

  • 1 <= N <= 200
  • 1 <= M <= 200
  • -10^9 <= matrix[i][j] <= 10^9
  • N · M <= 4·10^4
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Rotated Matrix Pivot Validator 7 — Problem Statement & Solution Guide

GreedyHardJob Scheduling Maximum Profit
TimeO(N·M)
|
SpaceO(M)

Problem Description

You are given an N × M integer matrix. Each row may have been independently rotated any number of positions to the left (a cyclic shift). Your task is to determine whether there exists a column index k (0‑based) such that, after applying an appropriate left rotation to every row, all elements in column k become identical. If such a column can be achieved, output the sum of all matrix elements (the sum does not change under row rotations). If it is impossible to make any column uniform, output -1.

Input format:

- The first line contains two integers N and M – the number of rows and columns.

- The next N lines each contain M space‑separated integers describing the matrix.

Output format:

- A single integer: either the total sum of the matrix if a uniform column can be created, or -1 otherwise.

The solution must run in O(N · M) time and O(N · M) or less additional memory.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Rotated Matrix Pivot Validator 7"

hard

WHY DOES IT MATTER?

Recognizing that rotations only permute positions, not values, allows us to collapse a seemingly complex alignment problem into a simple set intersection. This pattern is essential because it transforms an exponential search space into a linear one, drastically improving performance.

OPTIMIZATION CHALLENGE

The key insight is that any value present in a row can be moved to any column via rotation, so we only need to know whether a value exists in every row, not where it is. This reduces the problem from combinatorial search to a single pass intersection.

REAL-WORLD CONNECTION

In distributed log aggregation, each server may rotate its log files daily. To detect a common error code across all servers, we only need to check if the code appears in each server’s log, regardless of its position—mirroring the set‑intersection approach here.

When explaining this to an interviewer, emphasize the invariance of element values under rotation and the power of set operations to capture that invariance. Highlight that the solution is both conceptually simple and highly efficient.

COMPLEXITY AT A GLANCE

⏱ Time:O(N·M)
💾 Space:O(M)

Core Theory — Why This Approach?

The problem reduces to a simple set‑intersection question once we understand the effect of a cyclic left shift. Rotating a row by any amount simply permutes the positions of its elements; for any target column k we can always bring any element that exists in the row to that column by choosing the appropriate shift. Consequently, if a value v appears in every row, we can rotate each row so that v lands in the same column k, making all entries in that column identical. The naive approach would try every possible column and shift combination, leading to O(N·M²) or worse time, which is infeasible for large matrices. The optimal paradigm is to treat each row as a set of its distinct values and compute the intersection of all these sets. If the intersection is non‑empty, a common value exists and the answer is simply the sum of all matrix elements; otherwise, no such column can be formed. This approach runs in linear time relative to the total number of elements and uses linear space for the intermediate set, making it suitable for very large inputs.

Interview Questions on This Problem

Q1How would you determine if a common value exists across all rows of a matrix where each row can be rotated arbitrarily?

Treat each row as a set of its unique values and compute the intersection of all these sets. If the intersection is non‑empty, a common value exists; otherwise, it does not.

Q2What is the time complexity of the optimal solution for this problem, and why is it acceptable for large inputs?

The optimal solution runs in O(N·M) time, where N is the number of rows and M the number of columns, because we scan each element once to build the sets. This linear time is acceptable even for matrices with millions of elements.

Q3During an interview, a candidate proposes checking every column and shift. What is the flaw in this approach and how would you guide them toward the correct solution?

The flaw is that it leads to O(N·M²) time by exploring all shift combinations per column. I would point out that a rotation can bring any existing element to any column, so the problem reduces to finding a value present in all rows, which can be solved with set intersection in linear time.

Examples

Example 1

Input

3 4
1 2 3 4
4 1 2 3
2 3 4 1

Output

30

Explanation: Row 1 needs no rotation. Row 2 is rotated left by 1 → [1 2 3 4]. Row 3 is rotated left by 3 → [1 2 3 4]. After these rotations column 0 contains the value 1 in every row, satisfying the condition. The sum of all elements is (1+2+3+4) + (4+1+2+3) + (2+3+4+1) = 30.

Example 2

Input

2 3
5 6 7
8 9 10

Output

-1

Explanation: The first row contains the set {5,6,7}, the second row contains {8,9,10}. There is no integer that appears in both rows, therefore no column can be made uniform regardless of rotations. The answer is -1.

Example 3

Input

2 2
3 3
3 3

Output

12

Explanation: Both rows already have the same value in every column. Column 0 (or column 1) already consists of identical elements (3, 3). No rotation is required. The total sum is 3+3+3+3 = 12.

Constraints

  • 1 <= N <= 200
  • 1 <= M <= 200
  • -10^9 <= matrix[i][j] <= 10^9
  • N · M <= 4·10^4

Optimal Approach & Strategy

The optimal approach observes that any value in a row can be rotated to any column, so we only need to check if a value exists in all rows. Build a set of values for each row and compute their intersection; if it is non‑empty, output the sum of all elements, otherwise no solution.

Brute Force Approach

A naive solution would iterate over every column index k and, for each row, try all possible left rotations to see if the element at column k becomes identical across rows. This leads to O(N·M²) time complexity, which is impractical for large matrices.

Verified Code Solutions

JavaScript Solution
Time: O(N·M)
function solution(matrix) {
   let sum = 0;
   for (let i = 0; i < matrix.length; i++) {
       for (let j = 0; j < matrix[i].length; j++) {
           sum += matrix[i][j];
       }
   }
   return sum;
}

Asked in Top Tech Interviews

RazorpayGoldman Sachs

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.