AlgoDaily

Find in Shifted Sorted Matrix

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Question

Understanding the Matrix Shift Problem

Suppose you have a matrix where each row and column is sorted in ascending order. Your task is to apply two specific types of shifts, described below, and locate a given element x in the transformed matrix.

Shift Types

Left Circular Shift (l): - Definition: Moves the first column to the last position, shifting all other columns one step left. - Example:

 Before:
 ```py
 [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
 ]
 ```
 After:
 ```py
 [
    [2, 3, 1],
    [5, 6, 4],
    [8, 9, 7]
 ]
 ```
  • Visual Explanation: Imagine the columns on a circular conveyor belt. The first column wraps to the end, while others shift left.

Top Circular Shift (u): - Definition: Moves the first row to the last position, shifting all other rows one step up. - Example:

 Before:
 ```py
 [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
 ]
 ```
 After:
 ```py
 [
    [4, 5, 6],
    [7, 8, 9],
    [1, 2, 3]
 ]
 ```
  • Visual Explanation: Picture the rows on a circular escalator. The first row descends to the bottom, while others shift up.
Applying the Shifts to a Specific Example

Let's consider a sequence of shifts like [l,u,l,u,u] and apply them to the given matrix:

matrix = [
    [ 1, 2, 3, 4, 5],
    [ 6, 7, 8, 9,10],
    [11,12,13,14,15],
    [16,17,18,19,20]
]

After applying these rotations, the matrix transforms to:

matrix = [
    [9 ,10, 6, 7, 8],
    [14,15,11,12,13],
    [19,20,16,17,18],
    [ 4, 5, 1, 2, 3]
]

Here's an illustration to help visualize the problem: Problem Illustration

Your Task

Given this final matrix and a specific value x, how can you efficiently find the location of this element in the array and return it?

Constraints
  1. Matrix Size: Up to 10^5 x 10^5
  2. Time Complexity: O(nlogn)
  3. Memory Complexity: O(1)
  4. Element Existence: The value x is in the matrix.
  5. Minimum Elements: At least 1 element in the matrix.
  6. Sorting Order: Always sorted in all rows and columns.
  7. Uniqueness: Contains unique elements.

Considering these constraints and the above example, can you develop a method to locate the specified element in the transformed matrix?

```py
def findElementInMatrix(matrix, x):
    # Fill in

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →