K'th Element in Spiral Form of Matrix

Last Updated : 2 May, 2026

Given a matrix mat[][] and a number k, find the k-th element obtained while traversing the matrix in spiral order.

Examples:

Input: mat [][] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], k = 10
Output: 13
Explanation:

1

The spiral order of matrix will look like 1->2->3->4->8->12->16->15->14->13->9->5->6->7->11->10. So the 10th element in this order is 13.

Input: mat[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], k = 4
Output: 6
Explanation: Spiral traversal of matrix: {1, 2, 3, 6, 9, 8, 7, 4, 5}. Fourth element is 6.

Try It Yourself
redirect icon

Simple Simulation Approach- O(n × m) Time and O(1) Space

The idea is to traverse the matrix in spiral order starting from the top-left corner and maintain a counter to track the number of elements visited. A variable count is initialized to 0, and it is incremented each time an element is visited during the traversal. As soon as count becomes equal to k, the current element is returned as the answer. The matrix is traversed layer by layer in spiral form, ensuring all elements are visited in the correct order until the k-th element is found.

C++
#include <iostream>
#include<vector>
using namespace std;

// finds kth element in spiral traversal
int findK(vector<vector<int>> &mat, int k) {
    int m = mat.size();
    int n = mat[0].size();

    int count = 0;
    int last = -1;

    int top = 0, bottom = m - 1;
    int left = 0, right = n - 1;

    while (top <= bottom && left <= right && count < k) {

        // top row
        for (int i = left; i <= right && count < k; i++) {
            last = mat[top][i];
            count++;
        }
        top++;

        // right column
        for (int i = top; i <= bottom && count < k; i++) {
            last = mat[i][right];
            count++;
        }
        right--;

        // bottom row
        if (top <= bottom) {
            for (int i = right; i >= left && count < k; i--) {
                last = mat[bottom][i];
                count++;
            }
            bottom--;
        }

        // left column
        if (left <= right) {
            for (int i = bottom; i >= top && count < k; i--) {
                last = mat[i][left];
                count++;
            }
            left++;
        }
    }

    return last;
}

int main() {

    vector<vector<int>> mat = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    int k = 4;
    cout << findK(mat, k);
    return 0;
}
Java
class GFG {
   
 // finds kth element in spiral traversal
 public static int findK(int[][] mat, int k) {
        int m = mat.length;
        int n = mat[0].length;

        int top = 0, bottom = m - 1;
        int left = 0, right = n - 1;

        int count = 0, last = -1;

        while (top <= bottom && left <= right && count < k) {

            // top row
            for (int i = left; i <= right && count < k; i++) {
                last = mat[top][i];
                count++;
            }
            top++;

            // right column
            for (int i = top; i <= bottom && count < k; i++) {
                last = mat[i][right];
                count++;
            }
            right--;

            // bottom row
            if (top <= bottom) {
                for (int i = right; i >= left && count < k; i--) {
                    last = mat[bottom][i];
                    count++;
                }
                bottom--;
            }

            // left column
            if (left <= right) {
                for (int i = bottom; i >= top && count < k; i--) {
                    last = mat[i][left];
                    count++;
                }
                left++;
            }
        }

        return last;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int k = 4;
        System.out.println(findK(mat, k)); 
    }
}
Python
# finds kth element in spiral traversal
def findK(mat, k):
    m = len(mat)
    n = len(mat[0])

    top, bottom = 0, m - 1
    left, right = 0, n - 1

    count = 0
    last = -1

    while top <= bottom and left <= right and count < k:

        # top row
        for i in range(left, right + 1):
            if count == k:
                return last
            last = mat[top][i]
            count += 1
        top += 1

        # right column
        for i in range(top, bottom + 1):
            if count == k:
                return last
            last = mat[i][right]
            count += 1
        right -= 1

        # bottom row
        if top <= bottom:
            for i in range(right, left - 1, -1):
                if count == k:
                    return last
                last = mat[bottom][i]
                count += 1
            bottom -= 1

        # left column
        if left <= right:
            for i in range(bottom, top - 1, -1):
                if count == k:
                    return last
                last = mat[i][left]
                count += 1
            left += 1

    return last


if __name__ == "__main__":
    mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    k = 4
    print(findK(mat, k))
C#
using System;
using System.Collections.Generic;

class GFG {

    // finds kth element in spiral traversal
    public static int findK(List<List<int> > mat, int k)
    {
        int m = mat.Count;
        int n = mat[0].Count;

        int top = 0, bottom = m - 1;
        int left = 0, right = n - 1;

        int count = 0;
        int last = -1;

        while (top <= bottom && left <= right
               && count < k) {

            // top row
            for (int i = left; i <= right && count < k;
                 i++) {
                last = mat[top][i];
                count++;
            }
            top++;

            // right column
            for (int i = top; i <= bottom && count < k;
                 i++) {
                last = mat[i][right];
                count++;
            }
            right--;

            // bottom row
            if (top <= bottom) {
                for (int i = right; i >= left && count < k;
                     i--) {
                    last = mat[bottom][i];
                    count++;
                }
                bottom--;
            }

            // left column
            if (left <= right) {
                for (int i = bottom; i >= top && count < k;
                     i--) {
                    last = mat[i][left];
                    count++;
                }
                left++;
            }
        }

        return last;
    }

    public static void Main()
    {
        List<List<int> > mat = new List<List<int> >{
            new List<int>{ 1, 2, 3 },
            new List<int>{ 4, 5, 6 },
            new List<int>{ 7, 8, 9 }
        };
        int k = 4;
        Console.WriteLine(findK(mat, k));
    }
}
JavaScript
// finds kth element in spiral traversal
function findK(mat, k) {
    let m = mat.length;
    let n = mat[0].length;

    let last = -1;
    let count = 0;

    let top = 0, bottom = m - 1, left = 0, right = n - 1;

    while (top <= bottom && left <= right && count < k) {

        // top row
        for (let i = left; i <= right && count < k; i++) {
            last = mat[top][i];
            count++;
        }
        top++;

        // right column
        for (let i = top; i <= bottom && count < k; i++) {
            last = mat[i][right];
            count++;
        }
        right--;

        // bottom row 
        if (top <= bottom) {
            for (let i = right; i >= left && count < k; i--) {
                last = mat[bottom][i];
                count++;
            }
            bottom--;
        }

        // left column
        if (left <= right) {
            for (let i = bottom; i >= top && count < k; i--) {
                last = mat[i][left];
                count++;
            }
            left++;
        }
    }

    return last;
}

// Driver code
let mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let k = 6;

console.log(findK(mat, k)); 

Output
6

Optimized Layer- wise Traversal - O(max(n, m)) Time and O(max(n, m)) Space

The idea is to observe that spiral traversal proceeds in layers (or cycles). Each layer of the matrix consists of four sides: top row, right column, bottom row, and left column. Instead of traversing element by element, we can directly determine the position of the k-th element within a layer.

For a matrix of size m × n, a cycle can be divided into four parts:

  • If k ≤ m, the element lies in the first row
  • Else if k ≤ (m + n - 1), the element lies in the last column
  • Else if k ≤ (m + n - 1 + m - 1), the element lies in the last row
  • Else if k ≤ (m + n - 1 + m - 1 + n - 2), the element lies in the first column

If the k-th element is found in any of the above cases, it can be computed in constant time. Otherwise, we remove the outer cycle, reduce the matrix size, adjust the value of k, and recursively repeat the process until the element is found.

C++
#include <iostream>
#include<vector>
using namespace std;

int findKUtil(vector<vector<int>> &mat, int i,
    int j, int n, int m, int k) {

    if (n < 1 || m < 1)
        return -1;

    // If element is in outermost ring
    // Element is in first row
    if (k <= m)
        return mat[i][j + k - 1];

    // Element is in last column
    if (k <= (m + n - 1))
        return mat[i + (k - m)][j + m - 1];

    // Element is in last row
    if (k <= (m + n - 1 + m - 1))
        return mat[i + n - 1][j + m - 1 - (k - (m + n - 1))];

    // Element is in first column
    if (k <= (m + n - 1 + m - 1 + n - 2))
        return mat[i + n - 1 - (k - (m + n - 1 + m - 1))][j];

    return findKUtil(mat, i + 1, j + 1, n - 2, m - 2, k - (2 * n + 2 * m - 4));
}

int findK(vector<vector<int>> &mat, int k) {
    int n = mat.size();
    int m = mat[0].size();
    return findKUtil(mat, 0, 0, n, m, k);
}

int main() {
    vector<vector<int>> mat = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    int k = 4;
    cout << findK(mat, k);
    return 0;
}
Java
class GfG {

    static int findKUtil(int[][] mat, int i, int j,
                         int n, int m, int k) {

        if (n < 1 || m < 1)
            return -1;

        // First row
        if (k <= m)
            return mat[i][j + k - 1];

        // Last column
        if (k <= m + n - 1)
            return mat[i + (k - m)][j + m - 1];

        // Last row
        if (k <= m + n - 1 + m - 1)
            return mat[i + n - 1]
                      [j + m - 1 - (k - (m + n - 1))];

        // First column
        if (k <= m + n - 1 + m - 1 + n - 2)
            return mat[i + n - 1 -
                      (k - (m + n - 1 + m - 1))][j];

        // Move to inner matrix
        return findKUtil(
            mat,
            i + 1, j + 1,
            n - 2, m - 2,
            k - (2 * n + 2 * m - 4)
        );
    }

    static int findK(int[][] mat, int k) {
        int n = mat.length;
        int m = mat[0].length;
        return findKUtil(mat, 0, 0, n, m, k);
    }

    public static void main(String[] args) {

        int[][] mat = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int k = 4;
        System.out.println(findK(mat, k)); // Output: 6
    }
}
Python
def findKUtil(mat, i, j, n, m, k):

    if n < 1 or m < 1:
        return -1

    # If element is in outermost ring
    # Element is in first row
    if k <= m:
        return mat[i + 0][j + k - 1]

    # Element is in last column
    if k <= (m + n - 1):
        return mat[i + (k - m)][j + m - 1]

    # Element is in last row
    if k <= (m + n - 1 + m - 1):
        return mat[i + n - 1][j + 
            m - 1 - (k - (m + n - 1))]

    # Element is in first column
    if k <= (m + n - 1 + m - 1 + n - 2):
        return mat[i + n - 1 - 
            (k - (m + n - 1 + m - 1))][j + 0]

    return findKUtil(mat, i + 1, j + 1, n - 2, 
        m - 2, k - (2 * n + 2 * m - 4))

def findK(mat, k):
    n = len(mat)
    m = len(mat[0])
    return findKUtil(mat, 0, 0, n, m, k)

if __name__=="__main__":
    mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    k = 4
    print(findK(mat, k))
C#
using System;
using System.Collections.Generic;

class GfG {

    static int findKUtil(List<List<int>> mat, int i,
        int j, int n, int m, int k) {

        if (n < 1 || m < 1)
            return -1;

        // If element is in outermost ring
        // Element is in first row
        if (k <= m)
            return mat[i][j + k - 1];

        // Element is in last column
        if (k <= (m + n - 1))
            return mat[i + (k - m)][j + m - 1];

        // Element is in last row
        if (k <= (m + n - 1 + m - 1))
            return mat[i + n - 1][j + m - 1 - (k - (m + n - 1))];

        // Element is in first column
        if (k <= (m + n - 1 + m - 1 + n - 2))
            return mat[i + n - 1 - (k - (m + n - 1 + m - 1))][j];

        return findKUtil(mat, i + 1, j + 1, n - 2, 
            m - 2, k - (2 * n + 2 * m - 4));
    }

    static int findK(List<List<int>> mat, int k) {
        int n = mat.Count;
        int m = mat[0].Count;
        return findKUtil(mat, 0, 0, n, m, k);
    }

    public static void Main() {
        List<List<int>> mat = new List<List<int>> {
            new List<int> {1, 2, 3},
            new List<int> {4, 5, 6},
            new List<int> {7, 8, 9}
        };
        int k = 4;
        Console.WriteLine(findK(mat, k)); 
    }
}
JavaScript
function findKUtil(mat, i, j, n, m, k) {
    if (n < 1 || m < 1) return -1;

    // If element is in outermost ring
    // Element is in first row
    if (k <= m) return mat[i][j + k - 1];

    // Element is in last column
    if (k <= m + n - 1) return mat[i + (k - m)][j + m - 1];

    // Element is in last row
    if (k <= m + n - 1 + m - 1) 
        return mat[i + n - 1][j + m - 1 - (k - (m + n - 1))];

    // Element is in first column
    if (k <= m + n - 1 + m - 1 + n - 2) 
        return mat[i + n - 1 - (k - (m + n - 1 + m - 1))][j];

    return findKUtil(mat, i + 1, j + 1, n - 2, m - 2, k - (2 * n + 2 * m - 4));
}

function findK(mat, k) {
    let n = mat.length;
    let m = mat[0].length;
    return findKUtil(mat, 0, 0, n, m, k);
}

// Driver code
let mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
let k = 4;
console.log(findK(mat, k)); 

Output
6
Comment