Spiral Matrix | Practice | GeeksforGeeks

Given a matrix of size N x M. You have to find the Kth element which will obtain while traversing the matrix spirally starting from the top-left corner of the matrix.
Example 1:
Input: 
N = 3, M = 3, K = 4
A[] = {{1, 2, 3}, 
       {4, 5, 6}, 
       {7, 8, 9}}
Output: 
6
Explanation: Spiral traversal of matrix: 
{1, 2, 3, 6, 9, 8, 7, 4, 5}. Fourth element
is 6.

Example 2:
Input: 
N = 2, M = 2, K = 2 
A[] = {{1, 2},
       {3, 4}} 
Output: 
2
Explanation: Spiral traversal of matrix: 
{1, 2, 4, 3}. Second element is 2.
Your Task:  
You don't need to read input or print anything. Complete the function findK() which takes the matrix A[ ][ ], number of rows N, number of columns M, and integer K as input parameters and returns the Kth element in the spiral traversal of the matrix.
Expected Time Complexity: O(N*M)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ K ≤ N*M ≤ 106
0
pradeepsgrl121 month ago
	// time complexity o(n*m)
	// space complexity o(1)
	// if you like it please do upvote
	
	
	int findK(vector<vector<int>> &a, int n, int m, int k)
    {
        // Your code goes here
       
        int top=0,bottom=n,left=0,right=m;
        while(top<=bottom && left<=right){
            for(int i=left;i<right;i++){
                
                if(k==1)
                return a[top][i];
                k--;
            }
            top++;
            for(int i=top;i<bottom;i++){
                if(k==1)
                return a[i][right-1];
                k--;
            }
            right--;
            if(left<right){
                for(int i=right-1;i>=left;i--){
                    if(k==1)
                    return a[bottom-1][i];
                    k--;
                }
           
            }
             bottom--;
            if(top<bottom){
                for(int i=bottom-1;i>=top;i--){
                    if(k==1)
                    return a[i][left];
                    k--;
                }
                
            }
            left++;
        }
        
0
jayanth2643 months ago
int findK(vector<vector<int>> &mat, int r, int c, int k)   {       vector<int> ans;        int startrow=0;        int startcol=0;        int endrow=r-1;        int endcol=c-1;        int count=0;        int total=r*c;        while(count<total)        {            for(int index=startcol; index<=endcol && count<total; index++)            {                ans.push_back(mat[startrow][index]);                count++;            }            startrow++;                         for(int index=startrow; index<=endrow   && count<total; index++)            {                ans.push_back(mat[index][endcol]);                count++;            }            endcol--;                         for(int index=endcol; index>=startcol  && count<total; index--)            {                ans.push_back(mat[endrow][index]);                count++;            }            endrow--;                         for(int index=endrow; index>=startrow  && count<total; index--)            {                ans.push_back(mat[index][startcol]);                count++;            }            startcol++;                               }        return ans[k-1];   }
0
rohitpendse1386 months ago
Execution Time:- 1.6
 
class Solution {
public:
    int findK(vector<vector<int>> &a, int n, int m, int k) {
        // Your code goes here
        vector<int> ans;
        int top = 0, down = n - 1, left = 0, right = m - 1;
        int dir = 0;
        while (top <= down && left <= right) {
            if (dir == 0) {
                for (int i = left; i <= right; i++) {
                    ans.push_back(a[top][i]);
                }
                top++;
            } else if (dir == 1) {
                for (int i = top; i <= down; i++) {
                    ans.push_back(a[i][right]);
                }
                right--;
            } else if (dir == 2) {
                for (int i = right; i >= left; i--) {
                    ans.push_back(a[down][i]);
                }
                down--;
            } else if (dir == 3) {
                for (int i = down; i >= top; i--) {
                    ans.push_back(a[i][left]);
                }
                left++;
            }
            dir = (dir + 1) % 4;
        }
        return ans[k - 1];
    }
};
+1
badgujarsachin836 months ago
int findK(vector<vector<int>> &a, int n, int m, int k)
    {
        // Your code goes here
        vector<int> v;
        int top=0,bottom=n-1,left=0,right=m-1;
        while(top<=bottom && left<=right){
            for(int i=left;i<=right;i++){
                v.push_back(a[top][i]);
            }
            top++;
            for(int i=top;i<=bottom;i++){
                v.push_back(a[i][right]);
            }
            right--;
            if(left<=right){
                for(int i=right;i>=left;i--){
                    v.push_back(a[bottom][i]);
                }
           
            }
             bottom--;
            if(top<=bottom){
                for(int i=bottom;i>=top;i--){
                    v.push_back(a[i][left]);
                }
                
            }
            left++;
        }
        return v[k-1];
    }
-2
fungkwe7 months ago
For those of you who are bored or think it is too easy, let's try writing an O(1) (for both time and space) solution! There may be different approaches, but my hint is... (Hidden↓)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Sum of Arithmetic Sequence
+1
parvezkhan735142437 months ago
It is Very Easy Question
-1
sharma5120027 months ago
int findK(vector<vector<int>> &a, int n, int m, int k)
    {
        int startcol=0,startrow=0,rowboundary=n-1,columnboundary=m-1;
        int x=0,y;
        while(startrow<=rowboundary)
        {
            for(int i=startcol;i<=columnboundary;i++)
            {
                // cout<<a[startrow][i]<<' ';
                // x.push_back(a[startrow][i]);
                x++;
                y=a[startrow][i];
                if(x==k)
                {
                    return y;
                }
            }
            for(int i=startrow+1;i<=rowboundary;i++)
            {
                // cout<<a[i][columnboundary]<<' ';
                // x.push_back(a[i][columnboundary]);
                x++;
                y=a[i][columnboundary];
                if(x==k)
                {
                    return y;
                }
            }
            for(int i=columnboundary-1;i>=startcol;i--)
            {
                // cout<<a[rowboundary][i]<<' ';
                // x.push_back(a[rowboundary][i]);
                x++;
                y=a[rowboundary][i];
                if(x==k)
                {
                    return y;
                }
            }
            for(int i=rowboundary-1;i>startrow;i--)
            {
                // cout<<a[i][startcol]<<' ';
                // x.push_back(a[i][startcol]);
                x++;
                y=a[i][startcol];
                if(x==k)
                {
                    return y;
                }
            }
            startcol++;startrow++;rowboundary--;columnboundary--;
            // cout<<"\n"<<startrow<<' '<<startcol<<' '<<rowboundary<<' '<<columnboundary;
        }
        return 0;
    }
-2
iliyazali447 months ago
def findK(self, a, n, m, k):       # Your code goes here       ans=[]       left=0       right=m-1       up=0       down=n-1       c=0       while(len(ans)<n*m):           for i in range(left,right+1):               c+=1               ans.append(a[up][i])               if c==k:                   return ans[c-1]           for j in range(up+1,down+1):               c+=1               ans.append(a[j][right])               if c==k:                   return ans[c-1]           if up!=down:               for i in range(right-1,left-1,-1):                   c+=1                   ans.append(a[down][i])                   if c==k:                       return ans[c-1]           if left!=right:               for i in range(down-1,up,-1):                   c+=1                   ans.append(a[i][left])                   if c==k:                       return ans[c-1]           up+=1           right-=1           down-=1           left+=1       return ans[k-1]    
0
jevita2797 months ago
can someone tell me why dir variable is used in the editorial? my code failed a few test cases when it wasnt included;
-1
dashingrishigupta7 months ago
O(n) Solution
class Solution
{
public int findK(int a[][], int n, int m, int k)
{
    int s=0,i=0,N=n,M=m;
    while(n>0 && m>0) {
        int x = Math.max(1,(2*(n+m)) - 4);
        if(s+x>=k) break;
        s+=x;
        n-=2; m-=2;
        i++;
    }
    int y = k-s;
    if(y<=m) return a[i][i+y-1];
    else if(y<=m+n-1) return a[i+y-m][M-i-1];
    else if(y<=m+n-1+m-1) return a[N-i-1][M-i-1 - (y-(m+n-1))];
    else return a[N-i-1 - (y-(m+n-1+m-1))][i];
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.