Open In App

Insert and delete element from spirally sorted matrix

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Spirally Sorted 2D matrix mat[][] of size NXN, remove an element R and add another element A with only one traversal and without disrupting the sorted order. In other words, the matrix should remain in a spirally sorted form after both removal and addition operations.

Note: R will always be present in the Matrix to remove

Examples:

Input: mat[][] = [ [1, 2, 3],[8, 9, 4],[8, 6, 5] ], N = 3, R = 8, A = 7
Output: [ [1, 2, 3], [8, 9, 4], [7, 6, 5] ]
Explanation: The R is found at [2][0] index and A is inserted at the same place as 6<7<8.

matrix-(5)

Input: mat[][] = [ [1, 2],[4,3] ], N = 2, R = 1, A = 5
Output: [[2, 3], [5, 4]]
Explanation: The R is found at [0][0] index and all the upcoming values are shifted and then at the end A is inserted as 4<5.

Approach: To solve the problem follow the below idea:

  • If A > R, it removes R first and then appends A. Traverse the matrix in a spiral order, searching for the element R to be removed. Once R is found, it marks its position and shifts all subsequent elements backwards in the traversal to make space for A. When a position for A is found, it inserts A ensuring that the sorted order is maintained. If A is larger than all existing element, it is inserted at the end of the traversal.
  • If A < R, it appends A first and then removes R. Traverse the matrix in a spiral order, searching for the position for element A to be appended. Once A is appended, it marks its position and shifts all subsequent elements forward in the traversal to fill space of R.

Steps to solve the problem:

  • There are 3 cases that can occur in our problem.
    • If R=A, return matrix, as removing an element and then adding same element will not change the matrix.
    • If R<A, it means we will be first remove R and then append A. Start the spiral traversal.
      • If currentElement <= R, move to the next cell
      • If R < currentElement <= A, copy the currentElement to the previous cell
      • If currentElement > A, copy A to the previous cell and break.
      • If traversal reaches at the end insert A in the last position as A is the largest element of the matrix
    • If R>A, it means we will be first append A and then remove R. Maintain temp = A and Start the spiral traversal.
      • If currentElement <= A, move to the next cell
      • If A < currentElement < R, replace the currentElement with temp and store the replaced element in temp.
      • If A == R, replace the currentElement with temp and break.

Below is the implementation of the algorithm:

C++




// C++ Code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to insert and delete
// values from the matrix
void spiral_matrixAddRemove(vector<vector<int> >& mat,
                            int R, int A)
{
 
    // Appending and removing the same value
    // will result in the same matrix
    if (R == A) {
        return;
    }
 
    int rows = mat.size(), cols = mat[0].size();
    int top = 0, bottom = rows - 1, left = 0,
        right = cols - 1;
    // Femove then append
    if (R < A) {
        int prevX = -1, prevY = -1;
 
        // Spiral Traversal
        while (top <= bottom && left <= right) {
 
            // LEFT TO RIGHT
            for (int col = left; col <= right; col++) {
                if (mat[top][col] > A) {
 
                    // Insert A in place
                    // and return
                    mat[prevX][prevY] = A;
                    return;
                }
                if (mat[top][col] > R
                    && mat[top][col] <= A) {
 
                    // Shift these elements
                    mat[prevX][prevY] = mat[top][col];
                }
 
                // Store the index to shift
                // the upcoming values
                prevX = top;
                prevY = col;
            }
            top += 1;
 
            // TOP TO BOTTOM
            for (int row = top; row <= bottom; row++) {
                if (mat[row][right] > A) {
                    // Insert A in place
                    // and return
                    mat[prevX][prevY] = A;
                    return;
                }
                if (mat[row][right] > R
                    && mat[row][right] <= A) {
 
                    // Shift these elements
                    mat[prevX][prevY] = mat[row][right];
                }
                prevX = row;
                prevY = right;
            }
            right -= 1;
 
            // RIGHT TO LEFT
            if (top <= bottom && left <= right) {
                for (int col = right; col >= left; col--) {
                    if (mat[bottom][col] > A) {
 
                        // Insert A in place
                        // and return
                        mat[prevX][prevY] = A;
                        return;
                    }
                    if (mat[bottom][col] > R
                        && mat[bottom][col] <= A) {
                        // Shift these elements
                        mat[prevX][prevY]
                            = mat[bottom][col];
                    }
                    prevX = bottom;
                    prevY = col;
                }
                bottom -= 1;
 
                // BOTTOM TO TOP
                for (int row = bottom; row >= top; row--) {
 
                    // Similar to the previous loop
                    if (mat[row][left] > A) {
 
                        // Insert A in place
                        // and return
                        mat[prevX][prevY] = A;
                        return;
                    }
                    if (mat[row][left] > R
                        && mat[row][left] <= A) {
                        // Shift these elements
                        mat[prevX][prevY] = mat[row][left];
                    }
                    prevX = row;
                    prevY = left;
                }
                left += 1;
            }
        }
 
        // If we are not able to get a
        // value >= A, then it means A is the
        // largest value in the matrix Insert A
        // in the last available position
        mat[prevX][prevY] = A;
    }
 
    // First appending, then removing
    // needs to be done
    else {
 
        // After appending A, we get an extra
        // value, so we need to store the
        // extra value until we remove R
        int temp = A;
 
        // Spiral Traversal
        while (top <= bottom && left <= right) {
            // LEFT TO RIGHT
            for (int col = left; col <= right; col++) {
                if (mat[top][col] > A
                    && mat[top][col] < R) {
 
                    // Replace these elements
                    swap(temp, mat[top][col]);
 
                    // Check if the replaced
                    // element is the element
                    // to be removed
                    if (temp == R)
                        return;
                }
                else if (mat[top][col] == R) {
                    swap(temp, mat[top][col]);
                    return;
                }
            }
            top += 1;
 
            // TOP TO BOTTOM
            for (int row = top; row <= bottom; row++) {
                if (mat[row][right] > A
                    && mat[row][right] < R) {
                    // Replace these elements
                    swap(temp, mat[row][right]);
 
                    // Check if the replaced element
                    // is the element to be removed
                    if (temp == R)
                        return;
                }
                else if (mat[row][right] == R) {
                    swap(temp, mat[row][right]);
                    return;
                }
            }
            right -= 1;
 
            // RIGHT TO LEFT
            if (top <= bottom && left <= right) {
                for (int col = right; col >= left; col--) {
                    if (mat[bottom][col] > A
                        && mat[bottom][col] < R) {
                        // Replace these elements
                        swap(temp, mat[bottom][col]);
 
                        // Check if the replaced
                        // element is the element
                        // to be removed
                        if (temp == R)
                            return;
                    }
                    else if (mat[bottom][col] == R) {
                        swap(temp, mat[bottom][col]);
                        return;
                    }
                }
                bottom -= 1;
 
                // BOTTOM TO TOP
                for (int row = bottom; row >= top; row--) {
                    if (mat[row][left] > A
                        && mat[row][left] < R) {
 
                        // Replace these elements
                        swap(temp, mat[row][left]);
 
                        // Check if the replaced
                        // element is the element
                        // to be removed
                        if (temp == R)
                            return;
                    }
                    else if (mat[row][left] == R) {
                        swap(temp, mat[row][left]);
                        return;
                    }
                }
                left += 1;
            }
        }
    }
}
 
// Driver Code
int main()
{
    // Input
    vector<vector<int> > Matrix
        = { { 1, 2, 3 }, { 7, 9, 4 }, { 7, 6, 5 } };
    int R = 7, A = 8;
 
    // Functional call
    spiral_matrixAddRemove(Matrix, R, A);
 
    for (auto row : Matrix) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
 
    return 0;
}


Java




import java.util.Arrays;
 
public class SpiralMatrixAddRemove {
    // Function to insert and delete values from the matrix
    static void spiralMatrixAddRemove(int[][] mat, int R, int A) {
        // Appending and removing the same value will result in the same matrix
        if (R == A) {
            return;
        }
 
        int rows = mat.length, cols = mat[0].length;
        int top = 0, bottom = rows - 1, left = 0, right = cols - 1;
 
        // Remove then append
        if (R < A) {
            int prevX = -1, prevY = -1;
 
            // Spiral Traversal
            while (top <= bottom && left <= right) {
                // LEFT TO RIGHT
                for (int col = left; col <= right; col++) {
                    if (mat[top][col] > A) {
                        // Insert A in place and return
                        mat[prevX][prevY] = A;
                        return;
                    }
                    if (mat[top][col] > R && mat[top][col] <= A) {
                        // Shift these elements
                        mat[prevX][prevY] = mat[top][col];
                    }
                    prevX = top;
                    prevY = col;
                }
                top += 1;
 
                // TOP TO BOTTOM
                for (int row = top; row <= bottom; row++) {
                    if (mat[row][right] > A) {
                        // Insert A in place and return
                        mat[prevX][prevY] = A;
                        return;
                    }
                    if (mat[row][right] > R && mat[row][right] <= A) {
                        // Shift these elements
                        mat[prevX][prevY] = mat[row][right];
                    }
                    prevX = row;
                    prevY = right;
                }
                right -= 1;
 
                // RIGHT TO LEFT
                if (top <= bottom && left <= right) {
                    for (int col = right; col >= left; col--) {
                        if (mat[bottom][col] > A) {
                            // Insert A in place and return
                            mat[prevX][prevY] = A;
                            return;
                        }
                        if (mat[bottom][col] > R && mat[bottom][col] <= A) {
                            // Shift these elements
                            mat[prevX][prevY] = mat[bottom][col];
                        }
                        prevX = bottom;
                        prevY = col;
                    }
                    bottom -= 1;
 
                    // BOTTOM TO TOP
                    for (int row = bottom; row >= top; row--) {
                        if (mat[row][left] > A) {
                            // Insert A in place and return
                            mat[prevX][prevY] = A;
                            return;
                        }
                        if (mat[row][left] > R && mat[row][left] <= A) {
                            // Shift these elements
                            mat[prevX][prevY] = mat[row][left];
                        }
                        prevX = row;
                        prevY = left;
                    }
                    left += 1;
                }
            }
 
            // If we are not able to get a value >= A, then it means A is the
            // largest value in the matrix. Insert A in the last available position
            mat[prevX][prevY] = A;
        }
 
        // First appending, then removing needs to be done
        else {
            // After appending A, we get an extra value, so we need to store the
            // extra value until we remove R
            int temp = A;
 
            // Spiral Traversal
            while (top <= bottom && left <= right) {
                // LEFT TO RIGHT
                for (int col = left; col <= right; col++) {
                    if (mat[top][col] > A && mat[top][col] < R) {
                        // Replace these elements
                        int tempVal = temp;
                        temp = mat[top][col];
                        mat[top][col] = tempVal;
 
                        // Check if the replaced element is the element to be removed
                        if (temp == R)
                            return;
                    } else if (mat[top][col] == R) {
                        int tempVal = temp;
                        temp = mat[top][col];
                        mat[top][col] = tempVal;
                        return;
                    }
                }
                top += 1;
 
                // TOP TO BOTTOM
                for (int row = top; row <= bottom; row++) {
                    if (mat[row][right] > A && mat[row][right] < R) {
                        // Replace these elements
                        int tempVal = temp;
                        temp = mat[row][right];
                        mat[row][right] = tempVal;
 
                        // Check if the replaced element is the element to be removed
                        if (temp == R)
                            return;
                    } else if (mat[row][right] == R) {
                        int tempVal = temp;
                        temp = mat[row][right];
                        mat[row][right] = tempVal;
                        return;
                    }
                }
                right -= 1;
 
                // RIGHT TO LEFT
                if (top <= bottom && left <= right) {
                    for (int col = right; col >= left; col--) {
                        if (mat[bottom][col] > A && mat[bottom][col] < R) {
                            // Replace these elements
                            int tempVal = temp;
                            temp = mat[bottom][col];
                            mat[bottom][col] = tempVal;
 
                            // Check if the replaced element is the element to be removed
                            if (temp == R)
                                return;
                        } else if (mat[bottom][col] == R) {
                            int tempVal = temp;
                            temp = mat[bottom][col];
                            mat[bottom][col] = tempVal;
                            return;
                        }
                    }
                    bottom -= 1;
 
                    // BOTTOM TO TOP
                    for (int row = bottom; row >= top; row--) {
                        if (mat[row][left] > A && mat[row][left] < R) {
                            // Replace these elements
                            int tempVal = temp;
                            temp = mat[row][left];
                            mat[row][left] = tempVal;
 
                            // Check if the replaced element is the element to be removed
                            if (temp == R)
                                return;
                        } else if (mat[row][left] == R) {
                            int tempVal = temp;
                            temp = mat[row][left];
                            mat[row][left] = tempVal;
                            return;
                        }
                    }
                    left += 1;
                }
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args) {
        // Input
        int[][] matrix = { { 1, 2, 3 }, { 7, 9, 4 }, { 7, 6, 5 } };
        int R = 7, A = 8;
 
        // Functional call
        spiralMatrixAddRemove(matrix, R, A);
 
        // Printing the result
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}


Python3




# Python Implementation
def spiral_matrixAddRemove(mat, R, A):
    # Appending and removing the same value
    # will result in the same matrix
    if R == A:
        return
 
    rows = len(mat)
    cols = len(mat[0])
    top = 0
    bottom = rows - 1
    left = 0
    right = cols - 1
     
    # Remove then append
    if R < A:
        prevX = -1
        prevY = -1
 
        # Spiral Traversal
        while top <= bottom and left <= right:
 
            # LEFT TO RIGHT
            for col in range(left, right + 1):
                if mat[top][col] > A:
                    # Insert A in place and return
                    mat[prevX][prevY] = A
                    return
                if mat[top][col] > R and mat[top][col] <= A:
                    # Shift these elements
                    mat[prevX][prevY] = mat[top][col]
                prevX = top
                prevY = col
            top += 1
 
            # TOP TO BOTTOM
            for row in range(top, bottom + 1):
                if mat[row][right] > A:
                    # Insert A in place and return
                    mat[prevX][prevY] = A
                    return
                if mat[row][right] > R and mat[row][right] <= A:
                    # Shift these elements
                    mat[prevX][prevY] = mat[row][right]
                prevX = row
                prevY = right
            right -= 1
 
            # RIGHT TO LEFT
            if top <= bottom and left <= right:
                for col in range(right, left - 1, -1):
                    if mat[bottom][col] > A:
                        # Insert A in place and return
                        mat[prevX][prevY] = A
                        return
                    if mat[bottom][col] > R and mat[bottom][col] <= A:
                        # Shift these elements
                        mat[prevX][prevY] = mat[bottom][col]
                    prevX = bottom
                    prevY = col
                bottom -= 1
 
                # BOTTOM TO TOP
                for row in range(bottom, top - 1, -1):
                    if mat[row][left] > A:
                        # Insert A in place and return
                        mat[prevX][prevY] = A
                        return
                    if mat[row][left] > R and mat[row][left] <= A:
                        # Shift these elements
                        mat[prevX][prevY] = mat[row][left]
                    prevX = row
                    prevY = left
                left += 1
 
        # If we are not able to get a value >= A, then it means A is the
        # largest value in the matrix. Insert A in the last available position.
        mat[prevX][prevY] = A
     
    # First appending, then removing needs to be done
    else:
        temp = A
 
        # Spiral Traversal
        while top <= bottom and left <= right:
            # LEFT TO RIGHT
            for col in range(left, right + 1):
                if mat[top][col] > A and mat[top][col] < R:
                    # Replace these elements
                    temp, mat[top][col] = mat[top][col], temp
 
                    # Check if the replaced element is the element to be removed
                    if temp == R:
                        return
                elif mat[top][col] == R:
                    temp, mat[top][col] = mat[top][col], temp
                    return
            top += 1
 
            # TOP TO BOTTOM
            for row in range(top, bottom + 1):
                if mat[row][right] > A and mat[row][right] < R:
                    # Replace these elements
                    temp, mat[row][right] = mat[row][right], temp
 
                    # Check if the replaced element is the element to be removed
                    if temp == R:
                        return
                elif mat[row][right] == R:
                    temp, mat[row][right] = mat[row][right], temp
                    return
            right -= 1
 
            # RIGHT TO LEFT
            if top <= bottom and left <= right:
                for col in range(right, left - 1, -1):
                    if mat[bottom][col] > A and mat[bottom][col] < R:
                        # Replace these elements
                        temp, mat[bottom][col] = mat[bottom][col], temp
 
                        # Check if the replaced element is the element to be removed
                        if temp == R:
                            return
                    elif mat[bottom][col] == R:
                        temp, mat[bottom][col] = mat[bottom][col], temp
                        return
                bottom -= 1
 
                # BOTTOM TO TOP
                for row in range(bottom, top - 1, -1):
                    if mat[row][left] > A and mat[row][left] < R:
                        # Replace these elements
                        temp, mat[row][left] = mat[row][left], temp
 
                        # Check if the replaced element is the element to be removed
                        if temp == R:
                            return
                    elif mat[row][left] == R:
                        temp, mat[row][left] = mat[row][left], temp
                        return
                left += 1
 
# Driver Code
Matrix = [[1, 2, 3], [7, 9, 4], [7, 6, 5]]
R = 7
A = 8
 
spiral_matrixAddRemove(Matrix, R, A)
 
for row in Matrix:
    for val in row:
        print(val, end=" ")
    print()
 
# This code is contributed by Tapesh(tapeshdua420)


C#




using System;
 
class MainClass
{
    // Function to insert and delete values from the matrix
    public static void SpiralMatrixAddRemove(int[,] mat, int R, int A)
    {
        // Appending and removing the same value will result in the same matrix
        if (R == A)
        {
            return;
        }
 
        int rows = mat.GetLength(0);
        int cols = mat.GetLength(1);
        int top = 0, bottom = rows - 1, left = 0, right = cols - 1;
 
        // Remove then append
        if (R < A)
        {
            int prevX = -1, prevY = -1;
 
            // Spiral Traversal
            while (top <= bottom && left <= right)
            {
                // LEFT TO RIGHT
                for (int col = left; col <= right; col++)
                {
                    if (mat[top, col] > A)
                    {
                        // Insert A in place and return
                        mat[prevX, prevY] = A;
                        return;
                    }
                    if (mat[top, col] > R && mat[top, col] <= A)
                    {
                        // Shift these elements
                        mat[prevX, prevY] = mat[top, col];
                    }
                    prevX = top;
                    prevY = col;
                }
                top += 1;
 
                // TOP TO BOTTOM
                for (int row = top; row <= bottom; row++)
                {
                    if (mat[row, right] > A)
                    {
                        // Insert A in place and return
                        mat[prevX, prevY] = A;
                        return;
                    }
                    if (mat[row, right] > R && mat[row, right] <= A)
                    {
                        // Shift these elements
                        mat[prevX, prevY] = mat[row, right];
                    }
                    prevX = row;
                    prevY = right;
                }
                right -= 1;
 
                // RIGHT TO LEFT
                if (top <= bottom && left <= right)
                {
                    for (int col = right; col >= left; col--)
                    {
                        if (mat[bottom, col] > A)
                        {
                            // Insert A in place and return
                            mat[prevX, prevY] = A;
                            return;
                        }
                        if (mat[bottom, col] > R && mat[bottom, col] <= A)
                        {
                            // Shift these elements
                            mat[prevX, prevY] = mat[bottom, col];
                        }
                        prevX = bottom;
                        prevY = col;
                    }
                    bottom -= 1;
 
                    // BOTTOM TO TOP
                    for (int row = bottom; row >= top; row--)
                    {
                        // Similar to the previous loop
                        if (mat[row, left] > A)
                        {
                            // Insert A in place and return
                            mat[prevX, prevY] = A;
                            return;
                        }
                        if (mat[row, left] > R && mat[row, left] <= A)
                        {
                            // Shift these elements
                            mat[prevX, prevY] = mat[row, left];
                        }
                        prevX = row;
                        prevY = left;
                    }
                    left += 1;
                }
            }
 
            // If we are not able to get a value >= A, then it means A is the largest value in the matrix
            // Insert A in the last available position
            mat[prevX, prevY] = A;
        }
        // First appending, then removing needs to be done
        else
        {
            // After appending A, we get an extra value, so we need to store the extra value until we remove R
            int temp = A;
 
            // Spiral Traversal
            while (top <= bottom && left <= right)
            {
                // LEFT TO RIGHT
                for (int col = left; col <= right; col++)
                {
                    if (mat[top, col] > A && mat[top, col] < R)
                    {
                        // Replace these elements
                        int tempVal = temp;
                        temp = mat[top, col];
                        mat[top, col] = tempVal;
                        // Check if the replaced element is the element to be removed
                        if (temp == R)
                            return;
                    }
                    else if (mat[top, col] == R)
                    {
                        int tempVal = temp;
                        temp = mat[top, col];
                        mat[top, col] = tempVal;
                        return;
                    }
                }
                top += 1;
 
                // TOP TO BOTTOM
                for (int row = top; row <= bottom; row++)
                {
                    if (mat[row, right] > A && mat[row, right] < R)
                    {
                        // Replace these elements
                        int tempVal = temp;
                        temp = mat[row, right];
                        mat[row, right] = tempVal;
                        // Check if the replaced element is the element to be removed
                        if (temp == R)
                            return;
                    }
                    else if (mat[row, right] == R)
                    {
                        int tempVal = temp;
                        temp = mat[row, right];
                        mat[row, right] = tempVal;
                        return;
                    }
                }
                right -= 1;
 
                // RIGHT TO LEFT
                if (top <= bottom && left <= right)
                {
                    for (int col = right; col >= left; col--)
                    {
                        if (mat[bottom, col] > A && mat[bottom, col] < R)
                        {
                            // Replace these elements
                            int tempVal = temp;
                            temp = mat[bottom, col];
                            mat[bottom, col] = tempVal;
                            // Check if the replaced element is the element to be removed
                            if (temp == R)
                                return;
                        }
                        else if (mat[bottom, col] == R)
                        {
                            int tempVal = temp;
                            temp = mat[bottom, col];
                            mat[bottom, col] = tempVal;
                            return;
                        }
                    }
                    bottom -= 1;
 
                    // BOTTOM TO TOP
                    for (int row = bottom; row >= top; row--)
                    {
                        if (mat[row, left] > A && mat[row, left] < R)
                        {
                            // Replace these elements
                            int tempVal = temp;
                            temp = mat[row, left];
                            mat[row, left] = tempVal;
                            // Check if the replaced element is the element to be removed
                            if (temp == R)
                                return;
                        }
                        else if (mat[row, left] == R)
                        {
                            int tempVal = temp;
                            temp = mat[row, left];
                            mat[row, left] = tempVal;
                            return;
                        }
                    }
                    left += 1;
                }
            }
        }
    }
 
    public static void Main(string[] args)
    {
        // Input
        int[,] matrix = { { 1, 2, 3 }, { 7, 9, 4 }, { 7, 6, 5 } };
        int R = 7, A = 8;
 
        // Functional call
        SpiralMatrixAddRemove(matrix, R, A);
 
        // Displaying the resulting matrix
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}


Javascript




function spiralMatrixAddRemove(mat, R, A) {
  // Appending and removing the same value will result in the same matrix
  if (R === A) {
    return mat;
  }
   
  const rows = mat.length;
  const cols = mat[0].length;
  let top = 0;
  let bottom = rows - 1;
  let left = 0;
  let right = cols - 1;
 
  // Remove then append
  if (R < A) {
    let prevX = -1;
    let prevY = -1;
 
    // Spiral Traversal
    while (top <= bottom && left <= right) {
      // LEFT TO RIGHT
      for (let col = left; col <= right; col++) {
        if (mat[top][col] > A) {
          mat[prevX][prevY] = A;
          return mat;
        }
        if (mat[top][col] > R && mat[top][col] <= A) {
          mat[prevX][prevY] = mat[top][col];
        }
        prevX = top;
        prevY = col;
      }
      top += 1;
 
      // TOP TO BOTTOM
      for (let row = top; row <= bottom; row++) {
        if (mat[row][right] > A) {
          mat[prevX][prevY] = A;
          return mat;
        }
        if (mat[row][right] > R && mat[row][right] <= A) {
          // Shift these elements
          mat[prevX][prevY] = mat[row][right];
        }
        prevX = row;
        prevY = right;
      }
      right -= 1;
 
      // RIGHT TO LEFT
      if (top <= bottom && left <= right) {
        for (let col = right; col >= left; col--) {
          if (mat[bottom][col] > A) {
            // Insert A in place and return
            mat[prevX][prevY] = A;
            return mat;
          }
          if (mat[bottom][col] > R && mat[bottom][col] <= A) {
            // Shift these elements
            mat[prevX][prevY] = mat[bottom][col];
          }
          prevX = bottom;
          prevY = col;
        }
        bottom -= 1;
 
        // BOTTOM TO TOP
        for (let row = bottom; row >= top; row--) {
          if (mat[row][left] > A) {
            // Insert A in place and return
            mat[prevX][prevY] = A;
            return mat;
          }
          if (mat[row][left] > R && mat[row][left] <= A) {
            // Shift these elements
            mat[prevX][prevY] = mat[row][left];
          }
          prevX = row;
          prevY = left;
        }
        left += 1;
      }
    }
    // If we are not able to get a value >= A, then it means A is the
    // largest value in the matrix. Insert A in the last available position
    mat[prevX][prevY] = A;
  }
  // First appending, then removing needs to be done
  else {
    // After appending A, we get an extra value, so we need to store the
    // extra value until we remove R
    let temp = A;
 
    // Spiral Traversal
    while (top <= bottom && left <= right) {
      // LEFT TO RIGHT
      for (let col = left; col <= right; col++) {
        if (mat[top][col] > A && mat[top][col] < R) {
          // Replace these elements
          let tempVal = temp;
          temp = mat[top][col];
          mat[top][col] = tempVal;
          if (temp === R) return mat;
        } else if (mat[top][col] === R) {
          let tempVal = temp;
          temp = mat[top][col];
          mat[top][col] = tempVal;
          return mat;
        }
      }
      top += 1;
 
      // TOP TO BOTTOM
      for (let row = top; row <= bottom; row++) {
        if (mat[row][right] > A && mat[row][right] < R) {
          // Replace these elements
          let tempVal = temp;
          temp = mat[row][right];
          mat[row][right] = tempVal;
          // Check if the replaced element is the element to be removed
          if (temp === R) return mat;
        } else if (mat[row][right] === R) {
          let tempVal = temp;
          temp = mat[row][right];
          mat[row][right] = tempVal;
          return mat;
        }
      }
      right -= 1;
 
      // RIGHT TO LEFT
      if (top <= bottom && left <= right) {
        for (let col = right; col >= left; col--) {
          if (mat[bottom][col] > A && mat[bottom][col] < R) {
            // Replace these elements
            let tempVal = temp;
            temp = mat[bottom][col];
            mat[bottom][col] = tempVal;
            // Check if the replaced element is the element to be removed
            if (temp === R) return mat;
          } else if (mat[bottom][col] === R) {
            let tempVal = temp;
            temp = mat[bottom][col];
            mat[bottom][col] = tempVal;
            return mat;
          }
        }
        bottom -= 1;
 
        // BOTTOM TO TOP
        for (let row = bottom; row >= top; row--) {
          if (mat[row][left] > A && mat[row][left] < R) {
            // Replace these elements
            let tempVal = temp;
            temp = mat[row][left];
            mat[row][left] = tempVal;
            // Check if the replaced element is the element to be removed
            if (temp === R) return mat;
          } else if (mat[row][left] === R) {
            let tempVal = temp;
            temp = mat[row][left];
            mat[row][left] = tempVal;
            return mat;
          }
        }
        left += 1;
      }
    }
  }
 
  return mat;
}
 
// Driver Code
const mat = [
  [1, 2, 3],
  [7, 9, 4],
  [7, 6, 5]
];
const R = 7;
const A = 8;
 
// Functional call
const resultMatrix = spiralMatrixAddRemove(mat, R, A);
 
// Printing the result
resultMatrix.forEach(row => console.log(row));
 
//This code is contributed by Rohit Singh


Output

1 2 3 
8 9 4 
7 6 5 













Time Complexity: O(N * N), where N is the number of rows or columns in the input matrix
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads