Can You Overload or Override Static methods in Java

Can static method be overridden in Java, or can you override and overload static method in Java, is a common Java interview question, mostly asked to 2 years experienced Java programmers. Answer is, No, you can not override static method in Java, though you can declare method with same signature in sub class. It won’t be overridden in exact sense, instead that is called method hiding. But at same time, you can overload static methods in Java, there is nothing wrong declaring static methods with same name, but different arguments. Some time interviewer also ask, Why you can not override static methods in Java? Answer of this question lies on time of resolution. As I said in difference between static and dynamic binding , static method are bonded during compile time using Type of reference variable, and not Object. If you have using IDE like Netbeans and Eclipse, and If you try to access static methods using an object, you will see warnings. As per Java coding convention, static methods should be accessed by class name rather than object. In short Static method can be overloaded, but can not be overridden in Java. If you declare,  another static method with same signature in derived class than static method of super class will be hidden, and any call to that static method in sub class will go to static method declared in that class itself. This is known as method hiding in Java.

 

We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Nested Static Class in Java

A nested class is actually a member of a top-level class, so it’s not much difference with a static variable. All instances of the top-level class will have a reference of same nested class if its static, otherwise each of them will refer to a different instance of nested class.

One of the main advantages of making a nested class static is how you instantiate it. Suppose you declare a nested class B inside a top level class A, then it would be referred as A.B and you can create an instance of this class as A.B nestedStaticInstance = new A.B(), unlike Testing.B bs = new Testing(). new B(); for creating an instance of a non-static class, also known as inner class.

So, Yes, you can declare a class static in Java, provided the class is inside a top level class. Such classes are also known as nested classes and they can be declared static, but if you are thinking to make a top level class static in Java, then it’s not allowed. If you do so, the compiler will complain saying “illegal modifier for the class, only public, abstract and final are permitted”.

Now, let’s see some code in action to prove our point. First, let’s try to declare a top level class static in Java and see if we can do it or no.

How to make a static class in Java

You can see the compile-time error, it means it is illegal to use the static modifier with a top level class in Java. It doesn’t matter whether the class is public or package and whether its name is same as the name of the Java source file. In short, you cannot make a top level class static in Java i.e. the class which is not inside another class. Here is another example, where I have tried to make a non-public but top level class static in Java:

Can you make a class static in Java

You can see, still, the same compile time error, “illegal modifier for the class, only public, abstract and final are permitted” is thrown”.  If you are hearing about nested or inner class first time, You should first read a good core Java book e.g. Head First Java to learn more about nested class in Java.

Now, let’s try to make a nested class i.e. a class inside the top level class static in Java. As per theory, you can declare a nested class static in Java, let’s see that in code.

This time there is no compiler error, it means you can make a nested class static in Java. I have also shown you how you can create an instance of the nested static class in Java. You can see, you can create an instance without creating an instance of the outer class which was not possible with non-static nested class or inner class.

Can we declare a class Static in Java?

That’s all about whether you can declare a class static in Java or not. Of course, you cannot make a top level class static in Java but you can always make a nested class static in Java. In fact, it is one of the best practice and also suggested in Effective Java to prefer nested static class instead of non-static inner class.

We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Can we declare a class Static in Java?

The answer to this question is both Yes and No, depending on whether you are talking about a top level class or a nested class in Java. You cannot make a top level class static in Java, the compiler will not allow it, but you can make a nested class static in Java. A top level class is a class which is not inside another class. It may or may not be public i.e. you can have more than one class in a Java source file and only needs to be public, whose name must be same as the name of the file, rest of the class or interface on that file may or may not be public. On the other hand, a nested class is a class inside a top level class. It is also known as the inner class or member class in Java.

Now, let’s think about what is the meaning of static class, why would someone want to make a class static in Java? If you are familiar with concept of static method and static variable in Java, then you know that anything static can be accessed without creating instance of the class.

For example, you can access the static variable directly as ClassName.variable and you can invoke the static method as ClassName.staticMethod(), this is a great convenience for calling utility method or accessing constants.

This convenience is the main reason Java programmers like to declare nested class as static in Java. Remember, A nested class, if it’s not static then you can’t create its instance without first creating an instance of the outer class, which is a bit inconvenient. Such classes are known as Inner class and they are always associated with an instance of outer class.

We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at  http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Operator Overloading

/* C++ program to find the power of a given number using operator overloading concept*/

#include<iostream.h>
#include<conio.h>
#include<math.h>
int power(int,int);
float power(float,float);
void main()
{
int b,p,r;

float br,pr,rr;
clrscr();
cout<<“enter the integer base and integer power”;
cin>>b>>p;
cout<<“enter the real base and real power”;
cin>>br>>pr;
r=power(b,p); /* first function will be called*/
rr=power(br,pr); /* second function will be called*/
cout<<“the power of”<<b<<“and”<<p<<“is”<<r;
cout<<“\n”<<“the power of”<<br<<“and”<<pr<<“is”<<rr;
}
int power(int a,int b)
{
return pow(a,b);
}
float power(float c,float d)
{
return pow(c,d);
}

Output:
enter the integer base and integer power
2
2
enter the real base and real power
1.2
3.2
the power of 2 and 2 is 4
the power of 1.2 and 3.2 is 1.792

We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Move all negative elements to end in order with extra space allowed

Given an unsorted array of both negative and positive integer. The task is place all negative element at the end of array without changing the order of positive element and negative element.

Examples:

Input : arr[] = {1, -1, 3, 2, -7, -5, 11, 6 }
Output : 1  3  2  11  6  -1  -7  -5 

Input : arr[] = {-5, 7, -3, -4, 9, 10, -1, 11}
Output : 7  9  10  11  -5  -3  -4  -1

The problem becomes easier if we are allowed to use extra space. Idea is create an empty array (temp[]). First we store all positive element of given array and then we store all negative element of array in Temp[]. Finally we copy temp[] to original array.

Below implementation of above idea:

// C++ program to Move All -ve Element At End
// Without changing order Of Array Element
#include<bits/stdc++.h>
using namespace std;
// Moves all -ve element to end of array in
// same order.
void segregateElements(int arr[], int n)
{
    // Create an empty array to store result
    int temp[n];
    // Traversal array and store +ve element in
    // temp array
    int j = 0; // index of temp
    for (int i = 0; i < n ; i++)
        if (arr[i] >= 0 )
            temp[j++] = arr[i];
    // If array contains all positive or all negative.
    if (j == n || j == 0)
        return;
    // Store -ve element in temp array
    for (int i = 0 ; i < n ; i++)
        if (arr[i] < 0)
            temp[j++] = arr[i];
    // Copy contents of temp[] to arr[]
    memcpy(arr, temp, sizeof(temp));
}
// Driver program
int main()
{
    int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
    int n = sizeof(arr)/sizeof(arr[0]);
    segregateElements(arr, n);
    for (int i = 0; i < n; i++)
       cout << arr[i] << " ";
    return 0;
}

Output:

1 7 5 11 6 -1 -3 -2 

Time Complexity : O(n)
Auxiliary space : O(n)

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

Write a program to reverse an array or string

We are given an array (or string), the task is to reverse the array.

Examples:

Input  : arr[] = {1, 2, 3}
Output : arr[] = {3, 2, 1}

Input :  arr[] = {4, 5, 1, 2}
Output : arr[] = {2, 1, 5, 4}

Iterative way:
1) Initialize start and end indexes.
start = 0, end = n-1
2) In a loop, swap arr[start] with arr[end] and change start and end as follows.
start = start +1; end = end – 1

reverse-a-number

Another example to reverse a string:

reverse-a-string

// Iterative C program to reverse an array
#include<stdio.h>
/* Function to reverse arr[] from start to end*/
void rvereseArray(int arr[], int start, int end)
{
    int temp;
    while (start < end)
    {
        temp = arr[start];  
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }  
}    
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
  int i;
  for (i=0; i < size; i++)
    printf("%d ", arr[i]);
  printf("n");
}
/* Driver function to test above functions */
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    printArray(arr, 6);
    rvereseArray(arr, 0, 5);
    printf("Reversed array is n");
    printArray(arr, 6);   
    return 0;
}

Output:

1 2 3 4 5 6 
Reversed array is 
6 5 4 3 2 1

Time Complexity: O(n)

Recursive Way:
1) Initialize start and end indexes
start = 0, end = n-1
2) Swap arr[start] with arr[end]
3) Recursively call reverse for rest of the array.

// Recursive C program to reverse an array
#include <stdio.h>
/* Function to reverse arr[] from start to end*/
void rvereseArray(int arr[], int start, int end)
{
   int temp;
   if (start >= end)
     return;
   temp = arr[start];  
   arr[start] = arr[end];
   arr[end] = temp;
   rvereseArray(arr, start+1, end-1);  
}    
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
  int i;
  for (i=0; i < size; i++)
    printf("%d ", arr[i]);
  printf("n");
}
/* Driver function to test above functions */
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    printArray(arr, 5);
    rvereseArray(arr, 0, 4);
    printf("Reversed array is n");
    printArray(arr, 5);   
    return 0;
}

Output:

1 2 3 4 5 6 
Reversed array is 
6 5 4 3 2 1

Time Complexity: O(n)

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

Morgan Stanley Interview Experience | Set 32 (On-Campus)

Aptitude Test(90 mins, on Hackerrank)
7 aptitude questions based on Math and Logic<
7 Technical Subject Questions on Data Structures, 1 from OS(Few of them that I
remember)

    1. Hashing (Linear Probing)
    2. Counting Page Faults
    3. BST preorder and postorder
    4. Graph minimum distance
    5. Recursion(Given a recursive function f(int a),find f(8))
    6. Find Inorder successor in BST

2 Coding questions
1.String Manipulation
Given two Strings A and B of same length. You can replace any substring of A(i,j) with
substring of B(i,j).(Here note that substring from A and substring from B should have that same
start index and end index).find count of unique strings can be possible.answer might be
large.print answer%1000000007.

Note : Substring can be empty.
Test Case
1.
aaa
aaa
-> answer :1

Explanation : No matter what substring you replace,only one unique string is formed

i.e aaa.
2.
abc
xyz
-> answer :8


Explanation
:
8 different strings are possible…{abc , xyz , ayz , xbc , ayc , xbz , abz ,
xyc}

2. Matrix Problem
Given a square matrix A[][] of size N*N.Each element A[i][j] of matrix is red color or blue color.
Red ->1
Blue ->0
You are also given a number k.Find the side of largest square submatix having atmost k
red cells.

Constraints:
Size of matrix,N<=500

Test Case:
3 2 (N k)
1 1 1
1 0 1
1 1 0
Answer : 2

Explanation : Submatrix having top left corner (1,1) and bottom right corner (2,2) is the largest square submatrix having atmost 2( i.e k) red cells.

Onsite Interview
Round 1(Tech) :

    1. Java

1.Difference between abstract and interface?
2.“Animal” should be abstract class or interface?
3.Why java developers thought to introduce interface?
4.Few deep thinking questions on same abstract vs interface topic.
5.Polymorphic Reference in Java.

    1. Data Structures

1.Write recursive code for checking string palindrome or not.
2.Using stack and queue together,check if string is palindrome or not.
3.Given an array and a sum,find if there is any pair in array having sum equal to given
sum.(I used hashmap,so few questions about hashmap complexity)
4.Given an array and a sum,find if there is any triplet in array having sum equal to given
sum.

    1. OS

1.You want to run an animation and movie in your TV at the same time,how will you
schedule it?(Asked about using different scheduling algos)

    1. DBMS

2.Find tuple having third most highest salary in table.

Round 2(Group Activity)

10 candidates were selected from round 1,in this round we were given lego blocks.They told us
to work in a team and using that lego blocks build something(we made a solar panel house) in
30 mins.After that,there was a 5 min presentation about the product that we just built.We have
to impress investors to invest in our product.
Also write features of your product.Design Logo and name of your company.
Round 3(Tech – System Design)
Design a ticket booking portal for airplanes.You have apis of various airlines like JET
Airways,Indigo to get all the plane details.A user will come to your portal to book tickets.Using
apis,confirm availability of tickets from various airlines and book the tickets selected by users.
Design database structure,class diagrams,flow of system.

Round 4(HR)

1.About internship
2.Experience of working in groups
3.Coding experience
4.Who is your idol and why?
5.Why Morgan Stanley?

There was a re-interview of round 3
Design UBER.(database structure,OOP Model)
Some basics of compile time polymorphism.

Tips to follow :
Three years before

    1. Focus on academics.Score excellent grades in academics because only students above 8.5(last year 9)CGPA are allowed to give first round(aptitude round).
    2. Select a programming language like C,C++,Java,Python and start learning syntax and semantics of selected language.(Java would be a better option compared to others)

Two years before

    1. Start learning Data Structures,Java,DBMS,OS etc from standard reference books or online resources
    2. Solve algorithms from websites like geeksforgeeks , ideserve , careercup etc.
    3. Start coding in hackerrank and actively participate in all contests.Focus on improving performance in every contest.
    4. Look for internships

One year before

    1. Work on some big long-duration projects(So that you can show-off in your resume)
    2. Focus on building a well-balanced resume which should throw light on overall development of your personality.(Participate in GD,Debate,Sports activities,Coding competitions,Hackathon etc).
    3. Start coding in codechef,codeforces.

Few minutes before
Think of all the days and nights that you spent preparing for this interview!

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

Deloitte Interview Experience | Set 6 (On-Campus)

Work Location: Gurgaon
ELIGIBILITY: B.Tech/M.Tech/Dual – CS/IT/ECE (circuit branches ONLY) – 6 CGPA & above

Following was the process right from the start to the end of the selection process.

Round 1: Aptitude test
A common round for Deloitte India as well as Deloitte USI.
It was conducted by Aspiring minds (AMCAT)
It consisted of basic questions from Quants,Logical Reasoning and Verbal Ability. Out of some 900 students who appeared for the exam, 180 were shortlisted for Deloitte USI while 25 were for Deloitte India.

ROUND 2: 28th August, 2017: Deloitte India – JAM ON A CASE STUDY
The shortlisted 25 students were divided into two groups.
Each group was given a separate Case Study and 5 minutes were given for its analysis. Then, each candidate in the group was supposed to speak at least for a minute stating the situation and proposing their solution. Our group got a case study of a faulty ERP system in which multiple fake transactions were directed towards a particular vendor.

Note: This was not an elimination round.

ROUND 3: GROUP DISCUSSION
The group division was the same as in the previous round. Both groups were given topic related to the current affairs. Our topic was “Right to Privacy” and the other group got “Demonetization”. Candidates had to pitch in their opinions, some questions were specifically targeted to particular candidates. Judges were paying attention to not only how well we present our views, but also how keen we were listening to other’s opinions.

SHORTLISTING:
Based upon the combined scores of the above two rounds (JAM and GD), nine out of the 25 students were shortlisted for the interviews.

ROUND 4: TECHNICAL INTERVIEW
We were asked basic questions related to Computer Networking Concepts and Cyber Security which was a prerequisite for this profile. Some of the questions from networking were: IPv6 vs IPv4 addressing, Sub-netting, OSI/TCP model difference etc.
Then, some questions related to your college projects and elective subjects were asked. This went for around half an hour followed by an HR interview.

ROUND 5: HR INTERVIEW
This was not an interview, but just a chit-chat session. Questions were based on your resume such as your hobbies, interests etc. Then, the standard question – Why Deloitte?
The HR gave me a short feedback and asked if I had any questions.

WE were then asked to wait.

RESULTS

THREE students were selected for this profile from our college and I was one among them.

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

Inplace (Fixed space) M x N size matrix transpose | Updated

About four months of gap (missing GFG), a new post. Given an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it’s diagonal (try yourself). How to transpose an arbitrary size matrix inplace? See the following matrix,

a b c       a d g j
d e f  ==>  b e h k
g h i       c f i l
j k l

As per 2D numbering in C/C++, corresponding location mapping looks like,

Org element New
 0     a     0
 1     b     4
 2     c     8
 3     d     1
 4     e     5
 5     f     9
 6     g     2
 7     h     6
 8     i    10
 9     j     3
 10    k     7
 11    l    11

Note that the first and last elements stay in their original location. We can easily see the transformation forms few permutation cycles.

  • 1->4->5->9->3->1  – Total 5 elements form the cycle
  • 2->8->10->7->6->2 – Another 5 elements form the cycle
  • 0  – Self cycle
  • 11 – Self cycle

From the above example, we can easily devise an algorithm to move the elements along these cycles. How can we generate permutation cycles? Number of elements in both the matrices are constant, given by N = R * C, where R is row count and C is column count. An element at location ol (old location in R x C matrix), moved to nl (new location in C x R matrix). We need to establish relation between ol, nl, R and C. Assume ol = A[or][oc]. In C/C++ we can calculate the element address as,

ol = or x C + oc (ignore base reference for simplicity)

It is to be moved to new location nl in the transposed matrix, say nl = A[nr][nc], or in C/C++ terms

nl = nr x R + nc (R - column count, C is row count as the matrix is transposed)

Observe, nr = oc and nc = or, so replacing these for nl,

nl = oc x R + or -----> [eq 1]

after solving for relation between ol and nl, we get

ol     = or x C     + oc
ol x R = or x C x R + oc x R
       = or x N     + oc x R    (from the fact R * C = N)
       = or x N     + (nl - or) --- from [eq 1]
       = or x (N-1) + nl

OR,

nl = ol x R - or x (N-1)

Note that the values of nl and ol never go beyond N-1, so considering modulo division on both the sides by (N-1), we get the following based on properties of congruence,

nl mod (N-1) = (ol x R - or x (N-1)) mod (N-1)
             = (ol x R) mod (N-1) - or x (N-1) mod(N-1)
             = ol x R mod (N-1), since second term evaluates to zero
nl = (ol x R) mod (N-1), since nl is always less than N-1

A curious reader might have observed the significance of above relation. Every location is scaled by a factor of R (row size). It is obvious from the matrix that every location is displaced by scaled factor of R. The actual multiplier depends on congruence class of (N-1), i.e. the multiplier can be both -ve and +ve value of the congruent class.Hence every location transformation is simple modulo division. These modulo divisions form cyclic permutations. We need some book keeping information to keep track of already moved elements. Here is code for inplace matrix transformation,

// Program for in-place matrix transpose
#include <stdio.h>
#include <iostream>
#include <bitset>
#define HASH_SIZE 128
using namespace std;
// A utility function to print a 2D array of size nr x nc and base address A
void Print2DArray(int *A, int nr, int nc)
{
    for(int r = 0; r < nr; r++)
    {
        for(int c = 0; c < nc; c++)
            printf("%4d", *(A + r*nc + c));
        printf("\n");
    }
    printf("\n\n");
}
// Non-square matrix transpose of matrix of size r x c and base address A
void MatrixInplaceTranspose(int *A, int r, int c)
{
    int size = r*c - 1;
    int t; // holds element to be replaced, eventually becomes next element to move
    int next; // location of 't' to be moved
    int cycleBegin; // holds start of cycle
    int i; // iterator
    bitset<HASH_SIZE> b; // hash to mark moved elements
    b.reset();
    b[0] = b[size] = 1;
    i = 1; // Note that A[0] and A[size-1] won't move
    while (i < size)
    {
        cycleBegin = i;
        t = A[i];
        do
        {
            // Input matrix [r x c]
            // Output matrix 1
            // i_new = (i*r)%(N-1)
            next = (i*r)%size;
            swap(A[next], t);
            b[i] = 1;
            i = next;
        }
        while (i != cycleBegin);
        // Get Next Move (what about querying random location?)
        for (i = 1; i < size && b[i]; i++)
            ;
        cout << endl;
    }
}
// Driver program to test above function
int main(void)
{
    int r = 5, c = 6;
    int size = r*c;
    int *A = new int[size];
    for(int i = 0; i < size; i++)
        A[i] = i+1;
    Print2DArray(A, r, c);
    MatrixInplaceTranspose(A, r, c);
    Print2DArray(A, c, r);
    delete[] A;
    return 0;
}

Output:

   1   2   3   4   5   6
   7   8   9  10  11  12
  13  14  15  16  17  18
  19  20  21  22  23  24
  25  26  27  28  29  30

   1   7  13  19  25
   2   8  14  20  26
   3   9  15  21  27
   4  10  16  22  28
   5  11  17  23  29
   6  12  18  24  30

In given array of elements like [a1b2c3d4e5f6g7h8i9j1k2l3m4]. Convert it to [abcdefghijklm1234567891234]. The program should run inplace. What we need is an inplace transpose. Given below is code.

#include <stdio.h>
#include <iostream>
#include <bitset>
#define HASH_SIZE 128
using namespace std;
typedef char data_t;
void Print2DArray(char A[], int nr, int nc) {
   int size = nr*nc;
   for(int i = 0; i < size; i++)
      printf("%4c", *(A + i));
   printf("\n");
}
void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) {
   int size = r*c - 1;
   data_t t; // holds element to be replaced, eventually becomes next element to move
   int next; // location of 't' to be moved
   int cycleBegin; // holds start of cycle
   int i; // iterator
   bitset<HASH_SIZE> b; // hash to mark moved elements
   b.reset();
   b[0] = b[size] = 1;
   i = 1; // Note that A[0] and A[size-1] won't move
   while( i < size ) {
      cycleBegin = i;
      t = A[i];
      do {
         // Input matrix [r x c]
         // Output matrix 1
         // i_new = (i*r)%size
         next = (i*r)%size;
         swap(A[next], t);
         b[i] = 1;
         i = next;
      } while( i != cycleBegin );
      // Get Next Move (what about querying random location?)
      for(i = 1; i < size && b[i]; i++)
         ;
      cout << endl;
   }
}
void Fill(data_t buf[], int size) {
   // Fill abcd ...
   for(int i = 0; i < size; i++)
   buf[i] = 'a'+i;
   // Fill 0123 ...
   buf += size;
   for(int i = 0; i < size; i++)
      buf[i] = '0'+i;
}
void TestCase_01(void) {
   int r = 2, c = 10;
   int size = r*c;
   data_t *A = new data_t[size];
   Fill(A, c);
   Print2DArray(A, r, c), cout << endl;
   MatrixTransposeInplaceArrangement(A, r, c);
   Print2DArray(A, c, r), cout << endl;
   delete[] A;
}
int main() {
   TestCase_01();
   return 0;
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

Print a given matrix in spiral form

Given a 2D array, print it in spiral form. See the following examples.

Input:
        1    2   3   4
        5    6   7   8
        9   10  11  12
        13  14  15  16
Output: 
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 


Input:
        1   2   3   4  5   6
        7   8   9  10  11  12
        13  14  15 16  17  18
Output: 
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11

spiral-matrix

Solution:

/*#include <stdio.h>
#define R 3
#define C 6
void spiralPrint(int m, int n, int a[R][C])
{
    int i, k = 0, l = 0;
    /*  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator
    */
    while (k < m && l < n)
    {
        /* Print the first row from the remaining rows */
        for (i = l; i < n; ++i)
        {
            printf("%d ", a[k][i]);
        }
        k++;
        /* Print the last column from the remaining columns */
        for (i = k; i < m; ++i)
        {
            printf("%d ", a[i][n-1]);
        }
        n--;
        /* Print the last row from the remaining rows */
        if ( k < m)
        {
            for (i = n-1; i >= l; --i)
            {
                printf("%d ", a[m-1][i]);
            }
            m--;
        }
        /* Print the first column from the remaining columns */
        if (l < n)
        {
            for (i = m-1; i >= k; --i)
            {
                printf("%d ", a[i][l]);
            }
            l++;   
        }       
    }
}
/* Driver program to test above functions */
int main()
{
    int a[R][C] = { {1,  2,  3,  4,  5,  6},
        {7,  8,  9,  10, 11, 12},
        {13, 14, 15, 16, 17, 18}
    };
    spiralPrint(R, C, a);
    return 0;
}

Output:

1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 

Time Complexity: Time complexity of the above solution is O(mn).

 

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org