Close

Printing the matrix in a spiral order

Given a two dimensional array or a matrix, how do we write a program to print the elements in a spiral order. For example the spiral order for the following matrix is 1  2  3  4  8  12  16  15  14  13  9  5  6  7  11  10 1   2   3   4…

Given a doubly linked list, how do we reverse it by just re-arranging the pointers? Here is an example of input/output. The following picture depicts how we re-arrange the pointers. Here is the Java implementation.

Checking if any anagram of a given string is palindrome or not

Given a string, how do we check if any anagram of it can be a palindrome? For example let us consider the string “AAC”. An anagram of it is “ACA” which is a palindrome. We have to write a method which takes a string and outputs true if we can form a palindrome from any…

Given two sorted linked lists, how do we merge them without using any extra space. That means we have to re-arrange the links to form a single sorted linked list. For example let us consider the following two sorted lists as input. 1 -> 3 -> 5 -> 7 2 -> 4 -> 6 ->…

Merging k sorted lists

Given K sorted lists, how to merge them into a single sorted list? Let total number of elements in K sorted lists is N. We have to form a single sorted list of length N. For example let us consider the following input lists{4, 19, 27}{1, 6, 50, 73}{9, 45, 59, 67} The output should…

Level order traversal of a binary tree

Given a binary tree, we have to print the data level wise.  For example level order traversal of the following tree produces the sequence 5,3,8,2,4,6,1,7. The hint to solve this problem is to use a Queue data structure. We start by inserting the root node into the queue. Until the queue is empty, we remove…

Finding the minimum and maximum elements in a binary seach tree

Given a binary search tree, how do we find the maximum and minimum elements in it? For example in the given tree, the maximum element is 8 and the minimum element is 1. This algorithm is based on the following simple observation. In a Binary search tree, the minimum element always lies on the left…