Given a 2D Matrix of order n X m, print K’th element in the spiral form of the matrix. See the following examples.
Examples:
Input: mat[][] =
{{1, 2, 3, 4}
{5, 6, 7, 8}
{9, 10, 11, 12}
{13, 14, 15, 16}}
k = 6
Output: 12
Explanation: The elements in spiral order is
1, 2, 3, 4, 8, 12, 16, 15...
so the 6th element is 12
Input: mat[][] =
{{1, 2, 3, 4, 5, 6}
{7, 8, 9, 10, 11, 12}
{13, 14, 15, 16, 17, 18}}
k = 17
Output: 10
Explanation: The elements in spiral order is
1, 2, 3, 4, 5, 6, 12, 18, 17,
16, 15, 14, 13, 7, 8, 9, 10, 11
so the 17 th element is 10.
Simple Approah: One simple solution is to start traversing matrix in spiral form Print Spiral Matrix and start a counter i.e; count = 0. Whenever count gets equal to K, print that element.
- Algorithm:
- Keep a variable count = 0 to store the count.
- Traverse the matrix in sprial from start to end.
- Increase the count by 1 for every iteration.
- If the count is equal to the given value of k print the element and break.
-
Implementation
C++
#include <bits/stdc++.h>usingnamespacestd;#define R 3#define C 6voidspiralPrint(intm,intn,inta[R][C],intc){inti, k = 0, l = 0;intcount = 0;/* k - starting row indexm - ending row indexl - starting column indexn - ending column indexi - iterator*/while(k < m && l < n) {/* check the first row fromthe remaining rows */for(i = l; i < n; ++i) {count++;if(count == c)cout << a[k][i] <<" ";}k++;/* check the last columnfrom the remaining columns */for(i = k; i < m; ++i) {count++;if(count == c)cout << a[i][n - 1] <<" ";}n--;/* check the last row fromthe remaining rows */if(k < m) {for(i = n - 1; i >= l; --i) {count++;if(count == c)cout << a[m - 1][i] <<" ";}m--;}/* check the first column fromthe remaining columns */if(l < n) {for(i = m - 1; i >= k; --i) {count++;if(count == c)cout << a[i][l] <<" ";}l++;}}}/* Driver program to test above functions */intmain(){inta[R][C] = { { 1, 2, 3, 4, 5, 6 },{ 7, 8, 9, 10, 11, 12 },{ 13, 14, 15, 16, 17, 18 } },k = 17;spiralPrint(R, C, a, k);return0;}chevron_rightfilter_noneJava
importjava.io.*;classGFG {staticintR =3;staticintC =6;staticvoidspiralPrint(intm,intn,int[][] a,intc){inti, k =0, l =0;intcount =0;/* k - starting row indexm - ending row indexl - starting column indexn - ending column indexi - iterator*/while(k < m && l < n) {/* check the first row fromthe remaining rows */for(i = l; i < n; ++i) {count++;if(count == c)System.out.println(a[k][i]+" ");}k++;/* check the last columnfrom the remaining columns */for(i = k; i < m; ++i) {count++;if(count == c)System.out.println(a[i][n -1]+" ");}n--;/* check the last row fromthe remaining rows */if(k < m) {for(i = n -1; i >= l; --i) {count++;if(count == c)System.out.println(a[m -1][i]+" ");}m--;}/* check the first column fromthe remaining columns */if(l < n) {for(i = m -1; i >= k; --i) {count++;if(count == c)System.out.println(a[i][l]+" ");}l++;}}}/* Driver program to test above functions */publicstaticvoidmain (String[] args){inta[][] = { {1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18} };intk =17;spiralPrint(R, C, a, k);}}// This code is contributed by shivanisinghss2110chevron_rightfilter_nonePython3
R=3C=6defspiralPrint(m, n, a, c):k=0l=0count=0""" k - starting row indexm - ending row indexl - starting column indexn - ending column indexi - iterator"""while(k < mandl < n):foriinrange(l,n):count+=1if(count==c):print(a[k][i] , end=" ")k+=1""" check the last columnfrom the remaining columns """foriinrange(k,m):count+=1if(count==c):print(a[i][n-1],end=" ")n-=1""" check the last row fromthe remaining rows """if(k < m):foriinrange(n-1,l-1,-1):count+=1if(count==c):print(a[m-1][i],end=" ")m-=1""" check the first column fromthe remaining columns """if(l < n):foriinrange(m-1,k-1,-1):count+=1if(count==c):print(a[i][l],end=" ")l+=1""" Driver program to test above functions """a=[[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]k=17spiralPrint(R, C, a, k)# This code is contributed by shivanisinghchevron_rightfilter_none
Output:
10
- Complexity Analysis:
- Time Complexity : O(R*C), A single traversal of matrix is needed so the Time Complexity is O(R*C).
- Space Complexity : O(1), constant space is required.
Efficient Approach: While traversing the array in spiral order, a loop is used to traverse the sides. So if it can be found out that the kth element is in the given side then the kth element can be found out in constant time. This can be done recursively as well as iteratively.
- Algorithm :
- Traverse the matrix in form of spiral or cycles.
- So a cycle can be divided into 4 parts, so if the cycle is of size m X n.
- Element is in first row, i.e k <= m
- Element is in last column, i.e k <= (m+n-1)
- Element is in last row, i.e. k <= (m+n-1+m-1)
- Element is in first column, i.e k <= (m+n-1+m-1+n-2)
- If any of the above conditions meet then the kth element can be found is constant time.
- Else remove the cycle from the array and recursively call the function.
-
Implementation:
C++
// C++ program for Kth element in spiral// form of matrix#include <bits/stdc++.h>#define MAX 100usingnamespacestd;/* function for Kth element */intfindK(intA[MAX][MAX],intn,intm,intk){if(n < 1 || m < 1)return-1;/*....If element is in outermost ring ....*//* Element is in first row */if(k <= m)returnA[0][k - 1];/* Element is in last column */if(k <= (m + n - 1))returnA[(k - m)][m - 1];/* Element is in last row */if(k <= (m + n - 1 + m - 1))returnA[n - 1][m - 1 - (k - (m + n - 1))];/* Element is in first column */if(k <= (m + n - 1 + m - 1 + n - 2))returnA[n - 1 - (k - (m + n - 1 + m - 1))][0];/*....If element is NOT in outermost ring ....*//* Recursion for sub-matrix. &A;[1][1] isaddress to next inside sub matrix.*/returnfindK((int(*)[MAX])(&(A[1][1])), n - 2,m - 2, k - (2 * n + 2 * m - 4));}/* Driver code */intmain(){inta[MAX][MAX] = { { 1, 2, 3, 4, 5, 6 },{ 7, 8, 9, 10, 11, 12 },{ 13, 14, 15, 16, 17, 18 } };intk = 17;cout << findK(a, 3, 6, k) << endl;return0;}chevron_rightfilter_noneJava
// Java program for Kth element in spiral// form of matrixclassGFG {staticintMAX =100;/* function for Kth element */staticintfindK(intA[][],inti,intj,intn,intm,intk){if(n <1|| m <1)return-1;/*.....If element is in outermost ring ....*//* Element is in first row */if(k <= m)returnA[i +0][j + k -1];/* Element is in last column */if(k <= (m + n -1))returnA[i + (k - m)][j + m -1];/* Element is in last row */if(k <= (m + n -1+ m -1))returnA[i + n -1][j + m -1- (k - (m + n -1))];/* Element is in first column */if(k <= (m + n -1+ m -1+ n -2))returnA[i + n -1- (k - (m + n -1+ m -1))][j +0];/*.....If element is NOT in outermost ring ....*//* Recursion for sub-matrix. &A;[1][1] isaddress to next inside sub matrix.*/returnfindK(A, i +1, j +1, n -2,m -2, k - (2* n +2* m -4));}/* Driver code */publicstaticvoidmain(String args[]){inta[][] = { {1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18} };intk =17;System.out.println(findK(a,0,0,3,6, k));}}// This code is contributed by Arnab Kunduchevron_rightfilter_nonePython3
# Python3 program for Kth element in spiral# form of matrixMAX=100''' function for Kth element '''deffindK(A, n, m, k):if(n <1orm <1):return-1'''....If element is in outermost ring ....'''''' Element is in first row '''if(k <=m):returnA[0][k-1]''' Element is in last column '''if(k <=(m+n-1)):returnA[(k-m)][m-1]''' Element is in last row '''if(k <=(m+n-1+m-1)):returnA[n-1][m-1-(k-(m+n-1))]''' Element is in first column '''if(k <=(m+n-1+m-1+n-2)):returnA[n-1-(k-(m+n-1+m-1))][0]'''....If element is NOT in outermost ring ....'''''' Recursion for sub-matrix. &A;[1][1] isaddress to next inside sub matrix.'''A.pop(0)[j.pop(0)forjinA]returnfindK(A, n-2, m-2, k-(2*n+2*m-4))''' Driver code '''a=[[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]k=17print(findK(a,3,6, k))# This code is contributed by shivanisinghss2110chevron_rightfilter_none
Output:10
- Complexity Analysis:
- Time Complexity: O(c), where c is number of outer circular rings with respect to k’th element.
- Space Complexity: O(1).
As constant space is required.
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

