My blog performance in 2010 :-)

January 9, 2011

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image

The average container ship can carry about 4,500 containers. This blog was viewed about 21,000 times in 2010. If each view were a shipping container, your blog would have filled about 5 fully loaded ships.

In 2010, there were 17 new posts, not bad for the first year! There were 49 pictures uploaded, taking up a total of 710kb. That’s about 4 pictures per month.

The busiest day of the year was April 5th with 331 views. The most popular post that day was Diameter of a binary tree.

Where did they come from?

The top referring sites in 2010 were techpuzzl.wordpress.com, geeksforgeeks.org, discuss.techinterview.org, ocf.berkeley.edu, and google.co.in.

Some visitors came searching, mostly for naveen.garg iit slides|notes, pivoted array, and why does linkedlist repeat.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Diameter of a binary tree March 2010
4 comments

2

K – Reverse linked list March 2010
3 comments

3

Linked Lists March 2010

4

Count the number of occurrences of a element in a sorted array March 2010
1 comment

5

Trees March 2010


K – Reverse linked list

March 28, 2010

This is one of the questions asked in Microsoft Interview.

Given a linked list, we need to write a function that reverses the nodes of a linked list ‘k’ at a time and returns modified linked list.

The following are the constraints given:

  • If the no. of nodes in a link list is not a multiple of k then left-out nodes in the end should remain as it is
  • You have to retain the memory address of the nodes without modifying it i.e. you can’t just interchange the values in the nodes
  • Only constant memory is allowed

For example the linked list given is as follows:

Linked List : 1->2->3->4->5->6->7->8->9->10->11 -> null

For k = 2

Return Value: 2->1->4->3->6->5->8->7->10->9->11 ->null

For k = 3

Return value: 3->2->1->6->5->4->9->8->7->10->11 -> null

The following are the sequence of steps to be followed. In this solution, we will be using the reverse of a linked list solution described in previous post.

  • HeaderNode is the head of the linked list
  • Take three pointers StartNode, EndNode and NextNode
  • Let the NextNode pointer points to HeaderNode and unlink HeaderNode
  • Repeat the following steps until NextNode is null
    • Point StartNode and EndNode to NextNode
    • Move EndNode K nodes away from StartNode
    • Point NextNode to the node next to EndNode
    • Unlink EndNode from the linked list
    • Now reverse the list pointed by StartNode which gives reverse of K nodes
    • If HeaderNode is null point the HeaderNode to reversed list else point the reversed list to the end of the HeaderNode list
  • Hence the list pointed by HeaderNode contains the K- Reverse of a linked list

Read the rest of this entry »


Reverse a Single Linked List: Recursive Procedure

March 24, 2010

The following are the sequence of steps to be followed:

  • If the list is empty, then the reverse of the list is also empty
  • If the list has one element, then the reverse of the list is the element itself
  • If the list has n elements, then the reverse of the complete list is reverse of the list starting from second node followed by the first node element. This step is recursive step

The above mentioned steps can be described pictorially as shown below:

Consider the following linked list that needs to be reversed:

Dry run for the above example:

Take a pointer called SecondElementNode, which points to the second element of the list. Here the SecondElementNode points to 2.

Now we need to unlink the node pointed by HeaderNode. This step is to avoid cycle.

Reverse the list pointed by SecondElementNode recursively.

Now we have to append unlinked HeaderNode to the reversed list.

Code for the above solution:

Implementation for ListNode, SingleLinkedList are discussed in previous post.

package ds;

public class ReverseSingleListRecursive
{
    public ReverseSingleListRecursive()
    {
    }

    public ListNode reverseList(ListNode headerNode)
    {
        //  Reverse of a empty list or null list is null
        if (headerNode == null)
        {
            return null;
        }

        //  Reverse of a single element list is the list with that element
        if (headerNode.next == null)
        {
            return headerNode;
        }

        //  Reverse of n element list is reverse of the second element followed by first element

        //  Get the list node pointed by second element
        ListNode secondElementNode = headerNode.next;

        //  Unlink the first element
        headerNode.next = null;

        //  Reverse everything from the second element
        ListNode revNode = reverseList(secondElementNode);

        // Now we join both the lists
        secondElementNode.next = headerNode;

        return revNode;
    }

    public static void main(String[] args)
    {
        /*  Constructing Single Linked List:
            1 -> 2 ->3 -> 4 ->5 */
        SingleLinkedList newList = new SingleLinkedList();
        newList.add(1);
        newList.add(2);
        newList.add(3);
        newList.add(4);
        newList.add(5);
        System.out.println("List before reversal");
        newList.printList();

        ListNode headerNode = newList.getList();
        ReverseSingleListRecursive reverseListRecur = new ReverseSingleListRecursive();
        headerNode = reverseListRecur.reverseList(headerNode);
        newList.setList(headerNode);
        System.out.println("List after reversal");
        newList.printList();
    }
}

Please write comments if you find any of the above algorithms or codes incorrect, or find better ways to solve the same problem.


Reverse a Single Linked List: Iterative Procedure

March 24, 2010

This is one of the famous interview questions.

Following are two procedures to reverse a single linked list:

Iterative Procedure

The following are the sequence of steps to be followed:

  • Initially take three pointers: PrevNode, CurrNode, NextNode
  • Let CurrNode point to HeaderNode of the list. And let PrevNode and NextNode points to null
  • Now iterate through the linked list until CurrNode is null
  • In the loop, we need to change NextNode to PrevNode, PrevNode to CurrNode and CurrNode to NextNode

Consider the following linked list that needs to be reversed:

Dry run for the above example:

Taking 3 pointers: PrevNode, CurrNode and NextNode where CurrNode pointing to HeaderNode

After First Iteration:

After the first iteration of the loop, PrevNode points to the node containing element 1 and CurrNode & NextNode points to the node containing element 2. And the node pointed by PrevNode gets unlinked.

After Second Iteration:

After the second iteration of the loop, PrevNode Points to the node containing element 2 and CurrNode & NextNode point to the node containing element 3. And the CurrNode next would be pointing to PrevNode.

By the end of the iteration, PrevNode contains the reverse of the complete list.

Code for the above solution:

Implementation for ListNode, SingleLinkedList are discussed in previous post.

package ds;

public class ReverseSingleListIterative
{
    public ReverseSingleListIterative()
    {
    }

    public ListNode reverseList(ListNode headerNode)
    {
        ListNode prevNode = null;
        ListNode currNode = headerNode;
        ListNode nextNode = null;

        while (currNode != null)
        {
            nextNode = currNode.next;
            currNode.next = prevNode;
            prevNode = currNode;
            currNode = nextNode;
        }

        return prevNode;
    }

    public static void main(String[] args)
    {
        /*  Constructing Single Linked List:
            1 -> 2 ->3 -> 4 ->5 */
        SingleLinkedList newList = new SingleLinkedList();
        newList.add(1);
        newList.add(2);
        newList.add(3);
        newList.add(4);
        newList.add(5);
        System.out.println("List before reversal");
        newList.printList();

        ListNode headerNode = newList.getList();
        ReverseSingleListIterative reverseListIter = new ReverseSingleListIterative();
        headerNode = reverseListIter.reverseList(headerNode);
        newList.setList(headerNode);
        System.out.println("List after reversal");
        newList.printList();
    }
}

In the next post we will discuss how to reverse a single linked list using recursive procedure.

Please write comments if you find any of the above algorithms or codes incorrect, or find better ways to solve the same problem.


Find kth node from the end of linked list that contains loop

March 23, 2010

In previous posts (Loop in a linked list ,Calculate node that causes loop in a linked list and length of the list that contains loop) we discussed how to detect loop in a linked list, how to calculate node that causes loop in a linked list and how to find out length of the list that contains loop. In current post we discuss how to find kth node from end of the linked list that contains loop.

Finding kth node from the end of single linked list that does not contain loop is pretty much easy. Take two pointers one at the head of the list and one at k nodes from the head of the list. Traverse both the pointers simultaneously one at a time, by the time second pointer reaches end of the list, first pointer will be at kth position from the end of the list. Or if we know the length of the list in hand, traverse n-k nodes from the head of the list which gives kth node.

Following is the procedure to be followed to find kth node from the end of the linked list that contains a loop:

  • From previous post we know the loop detection node, merging point node, loop length and length of the list
  • If loop length >= k, we need to traverse loop length – k nodes from the merging point node
  • If loop length < k, we need to traverse length of list – k nodes from the head of linked list

Consider the following list that contains loop:

Dry run for the above example:

From previous posts, we know how to calculate merging point node, length of the loop and length of the list.

Consider the following figure:

To find 2nd node from the end of the list:

Here loopLength (4) > k (2).



To find 5th node from the end of the list:

Here loopLength (4) < k (5).

Read the rest of this entry »


Calculate length of the linked list that contains loop

March 17, 2010

In previous posts (Loop in a linked list and Calculate node that causes loop in a linked list) we discussed how to detect loop in a linked list and how to calculate node that causes loop in a linked list. In current post we discuss how to calculate length of the linked list when there is a loop in the linked list.

Following procedure explains how to calculate length of the linked list that contains loop:

  • Use the standard fast and slow pointer algorithm discussed in previous post to find the loop detection point
  • Take two pointers P1 and P2 at loop detection point. Place pointer P1 at the same place and move P2 forward one step at a time. Repeat until both the pointers meet together. Keep a count variable incremented for every iteration which gives length of the loop. Let say the length is L1
  • Again take two pointers P1 and P2. P1 at the head of the linked list and P2 at the loop detection point. Forward both the pointers one step at a time. Repeat until both the pointers meet together. This procedure is equivalent to the one we use to calculate node that causes loop in a linked list. Keep a count variable incremented for every iteration which gives the length of the list until the merging point. Let say the length is L2
  • Now the length of the list that contains loop is L1+ L2

Consider the following list that contains loop:

Dry run for the above example:

To calculate loop length:

Iteration 1:

Iteration 2:

Iteration 3:

Iteration 4:

Iteration 5:

From the above it is clear that loop length, L1 is 4.

Read the rest of this entry »


Calculate node that causes loop in a linked list

March 16, 2010

In previous post we discussed on how to detect a loop in linked list. In this post we will discuss how to find the node that causes loop in linked list.

Following procedure explains on how to detect node that caused loop:

  • By following the procedure described in previous post (Slow pointer and fast pointer approach),  we found the loop detection node
  • Now take pointers P1 and P2, P1 at the loop detection node and P2 starting from head of the linked list
  • Traverse both the pointers one at a time
  • Both the pointers meet at the node because of which there is a loop in the linked list

For example consider the following linked list where the loop is detected at node 5:

Dry run for the above example:

Take two pointers P1 and P2 pointing to node 1(head of the linked list) and node 5(loop detection point) respectively.

Iteration 1:

Iteration 2:

Iteration 3:

Here both of them meet at node that contains data as 3. Hence the node that causes loop in a linked list is node 3.

Implementation for class ListNode and class SingleLinkedList can be obtained from previous post.

Read the rest of this entry »


Loop in a linked list

March 16, 2010

A linked list is a data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence.

Lot of questions on linked lists appears in the interviews. Interviewers in these types of questions will be more interested on how we handle pointers, how we use linked list properties etc. In this series I discuss some of the questions that appear in interviews for the linked lists.

When working with singly linked list, we are typically given a link to the first node. Common operations on a singly linked list are iterating through all the nodes, adding to the list, or deleting from the list. Algorithms for these operations generally require a well formed linked list. That is a linked list without loops or cycles in it.

If a linked list has a cycle:

  • The malformed linked list has no end (no node ever has a null next pointer)
  • The malformed linked list contains two links to some node
  • Iterating through the malformed linked list will yield all nodes in the loop multiple times

A malformed linked list with a loop causes iteration over the list to fail because the iteration will never reach the end of the list. Therefore, it is desirable to be able to detect that a linked list is malformed before trying iteration.

The following are the questions that may arise in case of linked lists having loops:

In this post I will discuss how to detect a loop in a linked list.

To detect loop in a linked list

The standard linear time solution for this is as follows:

  • Take two pointers fast and slow
  • Increment slow pointer by one node (node.next) and fast pointer by two nodes (node.next.next)
  • If the two pointers merge at some point before the fast pointer reaches the end (this happens only if there is no loop), then there exists a loop in linked list

For example consider the following linked list:

Dry run for the above example:

Take two pointers Fast and Slow. Initially both of them point to beginning of the linked list.

Here in this example both points to 1. Increment slow pointer by one node (slow.next) and fast pointer by two nodes (fast.next.next). In this process if the linked list contains a loop, both of them meet at some point inside the loop.

Iteration 1:

Iteration 2:

Iteration 3:

Iteration 4:

Iteration 5:

Here both of them meet at node that contains data as 5. Hence there exists a loop in the linked list.

Read the rest of this entry »


Rebuild a binary tree from Inorder and Preorder traversals

March 15, 2010

This is a well known problem where given any two traversals of a tree  such as inorder & preorder or inorder & postorder or inorder & levelorder traversals we need to rebuild the tree.

The following procedure demonstrates on how to rebuild tree from given inorder and preorder traversals of a binary tree:

  • Preorder traversal visits Node, left subtree, right subtree recursively
  • Inorder traversal visits left subtree, node, right subtree recursively
  • Since we know that the first node in Preorder is its root, we can easily locate the root node in the inorder traversal and hence we can obtain left subtree and right subtree from the inorder traversal recursively

Consider the following example:

Preorder Traversal:    1    2    4    8    9    10    11    5    3    6    7

Inorder Traversal:       8    4    10    9    11    2    5    1    6    3    7

Iteration 1:

Root – {1}

Left Subtree – {8,4,10,9,11,2,5}

Right Subtree – {6,3,7}

Iteration 2:

Root – {2}

Left Subtree – {8,4,10,9,11}

Right Subtree – {5}

Root – {3}

Left Subtree – {6}

Right Subtree – {7}

Iteration 3:

Root – {2}

Left Subtree – {8,4,10,9,11}

Right Subtree – {5}

Root – {3}

Left Subtree – {6}

Right Subtree – {7}

Root – {4}

Left Subtree – {8}

Right Subtree – {10,9,11}

Done Done

Iteration 4:

Root – {2}

Left Subtree – {8,4,10,9,11}

Right Subtree – {5}

Root – {3}

Left Subtree – {6}

Right Subtree – {7}

Root – {4}

Left Subtree – {8}

Right Subtree – {10,9,11}

Done Done
Done R – {9}

Left ST – {10}

Right ST-{11}

Done Done

The following are the two versions of programming solutions even though both are based on above mentioned algorithm:

  • Creating left preorder, left inorder, right preorder, right inorder lists at every iteration to construct tree
  • Passing index of preorder and inorder traversals and using the same input list to construct tree

Implementation for Node, Tree, BinaryTree can be obtained from my previous post.

Read the rest of this entry »


Check whether given binary tree is a BST or not

March 12, 2010

A binary search tree is a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node’s key
  • The right subtree of a node contains only nodes with keys greater than the node’s key
  • Both the left and right subtrees must also be binary search trees

From the above it’s clear that each node in the binary search tree will have distinct key.

The following two solutions can be used to check whether given binary tree is a binary search tree or not:

  • For every node check whether its values is greater than maximum value of its left subtree and is less than minimum value of its right subtree
  • Traverse down the tree by keeping allowable minimum and maximum at every node

Consider following binary tree which is a binary search tree.

For every node check whether its values is greater than maximum value of its left subtree and is less than minimum value of its right subtree

This solution runs slowly because it traverses over some parts of the tree many times as we need to calculate maximum value of left subtree and minimum value of right subtree every time. The next solution is more efficient than this.

Code for the above solution is as follows:

Implementation for Node, Tree, BinaryTree can be obtained from my previous post.

package ds;

public class ISBst
{
    public ISBst()
    {
    }

    //  Returns true if a binary tree is a binary search tree
    public boolean isBST(Node node)
    {
        //  true for empty tree
        if(node == null)
        {
            return true;
        }

        //  false if the max of the left is > than current data
        if(node.left != null && maxValue(node.left) > node.data)
        {
            return false;
        }

        System.out.println(node.data);

        //  false if the min of the right is <= than current data
        if(node.right != null && minValue(node.right) <= node.data)
        {
            return false;
        }

        System.out.println(node.data);

        //  false if, recursively, the left or right is not a BST
        if(!isBST(node.left) || !isBST(node.right))
        {
            return false;
        }

        //  passing all that, it's a BST
        return true;
    }

    public int maxValue(Node node)
    {
        while(node.right != null)
        {
            node = node.right;
        }
        return node.data;
    }

    public int minValue(Node node)
    {
        while(node.left != null)
        {
            node = node.left;
        }
        return node.data;
    }

    public static void main(String[] args)
    {
        /*
        Constructing following tree
                         4
                    2          5
                1       3   NA      7

                                                        */
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.create(4);
        Node root = binaryTree.search(4);
        binaryTree.add(root, 2, BinaryTree.LEFT);
        binaryTree.add(root, 5, BinaryTree.RIGHT);
        binaryTree.add(binaryTree.search(2), 1, BinaryTree.LEFT);
        binaryTree.add(binaryTree.search(2), 3, BinaryTree.RIGHT);
        binaryTree.add(binaryTree.search(5), 7, BinaryTree.RIGHT);
        System.out.println("Binary Tree in level order is .... ");
        binaryTree.printLevelOrder();

        ISBst bTree = new ISBst();
        if(bTree.isBST(root))
        {
            System.out.println("Given binary tree is a binary search tree");
        }
        else
        {
            System.out.println("Given binary tree is not a binary search tree");
        }

    }
}

Traverse down the tree by keeping allowable minimum and maximum at every node

This solution traverses down the tree from root and checks whether the current node lies between allowable minimum and maximum values. Initial values for minimum value and maximum value will be Integer.MIN_VALUE and Integer.MAX_VALUE. (If we feel our data doesn’t lie between the above values, we need to traverse over the binary tree once and get minimum value and maximum value).

Code for the above solution is as follows:

Implementation for Node, Tree, BinaryTree can be obtained from my previous post.

package ds;

public class IsBstEfficient
{
    public IsBstEfficient()
    {

    }

    public boolean isBST(Node node)
    {
        return (isBST(node, Integer.MIN_VALUE, Integer.MAX_VALUE));
    }

    public boolean isBST(Node node, int minValue, int maxValue)
    {
        //  True is its a empty tree
        if(node == null)
        {
            return true;
        }

        //  False if this node violates the BST property
        if(node.data < minValue || node.data > maxValue)
        {
            return false;
        }

        //  Otherwise check the subtree recursively
        return (isBST(node.left, minValue, node.data) && isBST(node.right, node.data, maxValue));
    }

    public static void main(String[] args)
    {
        /*
        Constructing following tree
                         4
                    2          5
                1       3   NA      7

                                                        */
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.create(4);
        Node root = binaryTree.search(4);
        binaryTree.add(root, 2, BinaryTree.LEFT);
        binaryTree.add(root, 5, BinaryTree.RIGHT);
        binaryTree.add(binaryTree.search(2), 1, BinaryTree.LEFT);
        binaryTree.add(binaryTree.search(2), 3, BinaryTree.RIGHT);
        binaryTree.add(binaryTree.search(5), 7, BinaryTree.RIGHT);
        System.out.println("Binary Tree in level order is .... ");
        binaryTree.printLevelOrder();

        IsBstEfficient bTree = new IsBstEfficient();
        if(bTree.isBST(root))
        {
            System.out.println("Given binary tree is a binary search tree");
        }
        else
        {
            System.out.println("Given binary tree is not a binary search tree");
        }
    }
}

References:

http://en.wikipedia.org/wiki/Binary_search_tree

http://cslibrary.stanford.edu/110/BinaryTrees.html

Please write comments if you find any of the above algorithms or codes incorrect, or find better ways to solve the same problem.