Wednesday, October 17, 2018

ArrayList implementation

This ArrayList class mimics ArrayList of Java collection. The methods are all commented to make it easy for the readers. The code is available here.

List.java


package com.ds.adt.list;

/**
 * List interface includes all the methods that needs to be implemented by 
 * List type ADTs such as ArrayList, LinkedList, DoublyLinkedList etc.  
 * 
 * @author Pritam Banerjee
 * @version 15 October 2018
 */
public interface List<T> {

    public void add(T data);

    public void insert(T data, int position);

    public T get(int position);

    public void remove(T data);

    public void remove(int position);

    public void removeAll(List<T> data);

    public int size();
}



ArrayList.java

package com.ds.adt.list.array;

import java.lang.reflect.Array;
import com.ds.adt.list.List;

/**
 * Implements the List Interface and mimics Java's ArrayList
 *
 * @author Pritam Banerjee
 * @version 15 October 2018
 */

public class ArrayList<T> implements List<T> {

    /** Keeps track of the size of the array */
    private int size = 0;

    /** The total size of the array */
    private int capacity = 5;

    /** The actual resizable array */
    private T[] arr;

    /**
     * Constructor Declare the actual array
     */
    @SuppressWarnings("unchecked")
    public ArrayList() {
        arr = (T[]) new Object[capacity];
    }

    /**
     * Adds data to the list.
     * 
     * @param T data to be added
     */
    @Override
    public void add(T data) {
        if (size > capacity - 1) {
            resize();
        }
        arr[size] = data;
        size++;
    }

    /**
     * Used to insert in a particular position
     * 
     * @param T data
     * @param Integer position 
     */
    @Override
    public void insert(T data, int position) {
        if (position > size) {
            return;
        }
        Class<T> t = null;
        @SuppressWarnings("unchecked")
        T[] temp = (T[]) Array.newInstance(t, capacity);
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (position != i) {
                temp[count] = arr[i];
            } else {
                temp[position - 1] = data;
                temp[position] = arr[i];
            }
            count++;
        }
    }

    /**
     * Remove T data
     * 
     * @param T data to be deleted 
     */
    @Override
    public void remove(T data) {
        if (data == null)
            return;

        if (size == 0)
            return;

        int count = 0;
        @SuppressWarnings("unchecked")
        T[] temp = (T[]) new Object[size];
        for (int i = 0; i < size; i++) {
            if (!arr[i].equals(data)) {
                temp[count] = arr[i];
                count++;
            }
        }
        arr = temp;
        size = count;
    }

    /**
     * Remove all the elements of a List passed as a param 
     * 
     * @param position List
     */
    @Override
    public void removeAll(List<T> position) {
        for (int i = 0; i < position.size(); i++) {
            remove(position.get(i));
        }
    }

    /**
     * Returns the size of the list
     * 
     * @return size Integer
     */
    @Override
    public int size() {
        return size;
    }

    /**
    * Removes the element on a particular position 
    * 
    * @param position Integer
    */
    @Override
    public void remove(int position) {
        if (size == 0) {
            return;
        }
        if (position > size) {
            throw new IndexOutOfBoundsException();
        }

        @SuppressWarnings("unchecked")
        T[] temp = (T[]) new Object[capacity];
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (i != position) {
                temp[count] = arr[i];
                count++;
            }
        }
        arr = temp;
        size--;
    }

    /**
     * Returns the element on that position
     * 
     * @param position int
     * 
     * @return T 
     */
    @Override
    public T get(int position) {
        if (position < size) {
            return arr[position];
        }
        return null;
    }

    /**
     * Overrides object toString() method 
     * 
     * @return String 
     */
    @Override
    public String toString() {
        if (size == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append("arr[" + i + "] = " + arr[i] + " ");
            sb.append("\n");
        }
        return sb.toString();
    }

    /**
     * Resizes the array when capacity reaches a limit
     */
    @SuppressWarnings("unchecked")
    private void resize() {
        capacity = capacity * 2;
        T[] temp = (T[]) new Object[capacity];
        for (int i = 0; i < size; i++) {
            temp[i] = arr[i];
        }
        arr = temp;
    }

}


The following class gives a demo of the above ArrayList:

package com.ds.adt.list.array;

import com.ds.adt.list.List;

public class ArrayListDemo {

    public static void main(String[] args) {
        
        List<Integer> arrInteger = new ArrayList<Integer>();
        arrInteger.add(12);
        arrInteger.add(14);
        arrInteger.add(11);
        arrInteger.add(1);
        arrInteger.add(4);
        arrInteger.add(85);
       
        System.out.println(arrInteger);
        
        arrInteger.remove(2);
        
        System.out.println("After deleting 2");
        System.out.println(arrInteger);
        
        // Testing with Strings
        List<String> arrString = new ArrayList<>();
        
        System.out.println("String array: ");
        arrString.add("Pritam");
        arrString.add("Navi");
        arrString.add("Poda");
        arrString.add("Test");
        arrString.add("Molly");
        arrString.add("Piu");
       
        System.out.println(arrString);
        
        arrString.remove("Test");
        
        System.out.println("After deleting Test:");
        System.out.println(arrString);

    }


}

Interface for a List ADT(Abstract Data Type)


package com.ds.adt.list;

/**
 * List interface includes all the methods that needs to be implemented by 
 * List type ADTs such as ArrayList, LinkedList, DoublyLinkedList etc.  
 * 
 * @author Pritam Banerjee
 * @version 15 October 2018
 */
public interface List<T> {

    public void add(T data);

    public void insert(T data, int position);

    public T get(int position);

    public void remove(T data);

    public void remove(int position);

    public void removeAll(List<T> data);

    public int size();
}

Tuesday, September 18, 2018

Data Structure Questions and Answers



1. What is data structure?

Ans: Data structure refers to the way data is organized and manipulated. It seeks to find ways to make data access more efficient. When dealing with the data structure, we not only focus on one piece of data but also different sets of data and how they can relate to one another in an organized manner.


2. What is an array?

Ans: In programming terminology, an array is a collection of data or values where each value has an 'index' or location associated with it. An array incorporates, among others, a mechanism of accessing values placed in it (by index, usually, or by position in 'queue' or 'stack', referring to the first and last index), and a mechanism of manipulating it (adding values, changing or overwriting a value, deleting values etc.).

Arrays are stored in contiguous memory locations. And once declared they are usually of fixed size.


3. What is a Linked List?

Ans: A Linked List is a dynamic data structure. The number of nodes in a list is not fixed, unlike an array, and it can grow and shrink on demand. Any application which has to deal with an unknown number of objects may need to use a linked list.


4. What are the different types of Linked Lists?

Ans:
  1. Singly Linked List
  2. Doubly Linked List
  3. Circular Linked List

5. Can you briefly describe the types of Linked List?

Ans: Singly Linked List contain a head. Each Node stores the data and holds the reference to the next node in the linked list. And as in a linked list it can grow as per the need of the user.

Doubly Linked List contain a head and tail. Each Node stores a reference to the previous node and the next node along with the data. Doubly linked lists enable traversal in both directions and from both ends of the linked list. Hence it is useful for implementing Stack and Queue.

Circular Linked List is similar to Singly Linked list but the last node points to the head instead of null.

6. How is an Array different from Linked List?

Ans:
The size of the arrays is fixed, Linked Lists are Dynamic in size as it can grow when new nodes are added to it.
  • Inserting and deleting a new element in an array of elements is expensive. If you add an element to the end of an array you will need to traverse the whole array and then add it to the end. Also if you want to add it to the beginning then you will need to shift the rest of the elements to the right. Both these operations are O(n). But both insertion and deletion can easily be done in Linked Lists and can be achieved in O(1) time.
  • Random access is not allowed in Linked Listed. To access a particular node you will need to traverse the entire linked list which makes it O(n).
  • Extra memory space for a pointer is required with each element of the Linked list as it stores the reference to the next element. For doubly linked list it stores both the previous and next object reference.
  • Arrays have better cache locality that can make a pretty big difference in performance.
  • Arrays need contiguous memory allocation whereas linked list can have nodes anywhere in the memory thus making it more flexible.


Complexity(average) for Arrays:

Accessing elements: O(1) (Eg: arr[3], arr[i])

Adding or deleting: O(n)

Lookup/Search: O(n)

Complexities for Singly Linked List:

Insert in the beginning: O(1)

Insert in the end: O(n)

Deleting any node: O(n)

Deleting head: O(1)

Deleting tail: O(n)

Lookup/Search: O(n)

Complexities for Doubly Linked List:

Insert in the beginning: O(1)

Insert in the end: O(1)

Deleting any node: O(n)

Deleting head: O(1)

Deleting tail: O(1)

Lookup/Search: O(n)


7. Translate infix expression into its equivalent postfix expression:
Ans:

(A-B)*(D/E)

(A-B)*(D/E) = [AB-]*[DE/] = AB-DE/*


8. What are priority queues?
Ans: A priority queue is a collection of elements such that each element has been assigned a priority.

9. What is a string?
Ans: A sequential array of characters is called a string.

10. How do you reference all the elements in a one-dimension array?
Ans: To reference all the elements in a one -dimension array, you need to use an indexed loop, So that, the counter runs from 0 to the array size minus one. In this manner, You can reference all the elements in sequence by using the loop counter as the array subscript.

11. In what areas do data structures are applied?
Ans: Data structures are essential in almost every aspect where data is involved. In general, algorithms that involve efficient data structure are applied in the following areas: numerical analysis, operating system, A.I., compiler design, database management, graphics, and statistical analysis, to name a few.

12. What is LIFO?
Ans: LIFO is a short form of Last In First Out. It refers how data is accessed, stored and retrieved. Using this scheme, data that was stored last should be the one to be extracted first. This also means that in order to gain access to the first data, all the other data that was stored before this first data must first be retrieved and extracted.

13. What is a queue?
Ans: A queue is a data structure that can simulate a list or stream of data. In this structure, new elements are inserted at one end, and existing elements are removed from the other end.

14. What are binary trees?
Ans: A binary tree is a type of data structure that has two nodes, a left node, and a right node. In programming, binary trees are an extension of the linked list structures.

15. Which data structures are applied when dealing with a recursive function?
Ans: Recursion, is a function that calls itself based on a terminating condition. It makes use of the stack. Using LIFO, a call to a recursive function saves the return address so that it knows how to return to the calling function after the call terminates.

16. What is a stack?

Ans: A stack is a data structure in which only the top element can be accessed. As data is stored in the stack, each data is pushed downward, leaving the most recently added data on top.

Eg: Stack of dishes.

Compiler uses Stack to keep track of Recursion.

17. Explain Binary Search Tree.

Ans: A binary search tree stores data in such a way that they can be retrieved very efficiently. The left subtree contains nodes whose keys are less than the node’s key value, while the right subtree contains nodes whose keys are greater than or equal to the node’s key value. Moreover, both subtrees are also binary search trees.

18. What are multidimensional arrays?

Ans: Multidimensional arrays make use of multiple indexes to store data. It is useful when storing data that cannot be represented using single dimensional indexing, such as data representation in a board game, tables with data stored in more than one column.

19. Are linked lists considered linear or non-linear data structures?

Ans: It depends on where you intend to apply linked lists. If you based it on storage, a linked list is considered non-linear. On the other hand, if you based it on access strategies, then a linked list is considered linear.

20. How does dynamic memory allocation help in managing data?

Ans: Apart from being able to store simple structured data types, dynamic memory allocation can combine separately allocated structured blocks to form composite structures that expand and contract as needed.

21. What is FIFO?

Ans: FIFO stands for First-in, First-out, and is used to represent how data is accessed in a queue. Data has been inserted into the queue list the longest is the one that is removed first.

22. What is an ordered list?

Ans: An ordered list is a list in which each node’s position in the list is determined by the value of its key component, so that the key values form an increasing sequence, as the list is traversed.

23. What is merge sort?

Ans: Merge sort, is a divide-and-conquer approach for sorting the data. In a sequence of data, adjacent ones are merged and sorted to create bigger sorted lists. These sorted lists are then merged again to form an even bigger sorted list, which continues until you have one single sorted list.

24. Differentiate NULL and VOID.

Ans: Null is a value, whereas Void is a data type identifier. A variable that is given a Null value indicates an empty value. The void is used to identify pointers as having no initial size.

25. What is the primary advantage of a linked list?

Ans: A linked list is an ideal data structure because it can be modified easily. This means that editing a linked list works regardless of how many elements are in the list.

26. What is the difference between a PUSH and a POP?

Ans: Pushing and popping applies to the way data is stored and retrieved in a stack. A push denotes data being added to it, meaning data is being “pushed” into the stack. On the other hand, a pop denotes data retrieval, and in particular, refers to the topmost data being accessed.

Similar to Pop Stack supports another method called Peek which just shows the top element in the stack, but does not delete it.

27. What is a linear search?

Ans: A linear search refers to the way a target key is being searched in a sequential data structure. In this method, each element in the list is checked and compared against the target key. The process is repeated until found or if the end of the file has been reached.

28. How does variable declaration affect memory allocation?

Ans: The amount of memory to be allocated or reserved would depend on the data type of the variable being declared. For example, if a variable is declared to be of integer type, then 32 bits of memory storage will be reserved for that variable.

29. What is the advantage of the heap over a stack?

Ans: The heap is more flexible than the stack. That’s because memory space for the heap can be dynamically allocated and de-allocated as needed. However, the memory of the heap can at times be slower when compared to that stack.

30. What is a postfix expression?

Ans: A postfix expression is an expression in which each operator follows its operands. The advantage of this form is that there is no need to group sub-expressions in parentheses or to consider operator precedence.

31. What is Data abstraction?

Ans: Data abstraction is a powerful tool for breaking down complex data problems into manageable chunks. This is applied by initially specifying the data objects involved and the operations to be performed on these data objects without being overly concerned with how the data objects will be represented and stored in memory.

It is basically used to hide the implementation details from the user. It is achieved by encapsulation which is nothing but hiding the implementation details.

32. How do you insert a new item in a binary search tree?

Ans: Assuming that the data to be inserted is a unique value (that is, not an existing entry in the tree), check first if the tree is empty. If it’s empty, just insert the new item in the root node. If it’s not empty, refer to the new item’s key. If it’s smaller than the root’s key, insert it into the root’s left subtree, otherwise, insert it into the root’s right subtree.

33. How does a selection sort work for an array?

Ans: The selection sort is a fairly intuitive sorting algorithm, though not necessarily efficient. In this process, the smallest element is first located and switched with the element at subscript zero, thereby placing the smallest element in the first position.

The smallest element remaining in the subarray is then located next to subscripts 1 through n-1 and switched with the element at subscript 1, thereby placing the second smallest element in the second position. The steps are repeated in the same manner till the last element.

34. How do signed and unsigned numbers affect memory?

Ans: In the case of signed numbers, the first bit is used to indicate whether positive or negative, which leaves you with one bit short. With unsigned numbers, you have all bits available for that number. The effect is best seen in the number range (an unsigned 8-bit number has a range 0-255, while the 8-bit signed number has a range -128 to +127.

35. What is the minimum number of nodes that a binary tree can have?

Ans: A binary tree can have a minimum of zero nodes, which occurs when the nodes have NULL values. Furthermore, a binary tree can also have 1 or 2 nodes.

36. What are dynamic data structures?

Ans: Dynamic data structures are structures that expand and contract as a program runs. It provides a flexible means of manipulating data because it can adjust according to the size of the data.

37. What is the minimum number of queues needed when implementing a priority queue?

Ans: The minimum number of queues needed in this case is two. One queue is intended for sorting priorities while the other queue is used for actual storage of data.

38. Which sorting algorithm is considered the fastest?

Ans: There are many types of sorting algorithms: quick sort, bubble sort, balloon sort, radix sort, merge sort, etc. Not one can be considered the fastest because each algorithm is designed for a particular data structure and data set. It would depend on the data set that you would want to sort.

39. Differentiate STACK from ARRAY.

Ans: Stack follows a LIFO pattern. It means that data access follows a sequence wherein the last data to be stored when the first one to be extracted. Arrays, on the other hand, does not follow a particular order and instead can be accessed by referring to the indexed element within the array.

40. Give a basic algorithm for searching a binary search tree.

Ans:

  • If the tree is empty, then the target is not in the tree, end search
  • If the tree is not empty, the target is in the tree
  • Check if the target is in the root item
  • If a target is not in the root item, check if a target is smaller than the root’s value
  • If a target is smaller than the root’s value, search the left subtree
  • Else, search the right subtree.


41. What is a dequeue?

Ans: A dequeue is a double-ended queue. This is a structure wherein elements can be inserted or removed from either end.

42. What is a bubble sort and how do you perform it?

Ans: A bubble sort is one sorting technique that can be applied to data structures such as an array. It works by comparing adjacent elements and exchanges their values if they are out of order. This method lets the smaller values “bubble” to the top of the list, while the larger value sinks to the bottom.

43. What are the parts of a linked list?

Ans: A linked list typically has two parts: the head and the tail. Between the head and tail lie the actual nodes. All these nodes are linked sequentially.

44. How does selection sort work?

Ans: Selection sort works by picking the smallest number from the list and placing it at the front. This process is repeated for the second position towards the end of the list. It is the simplest sort algorithm.

45. Differentiate linear from a nonlinear data structure.

Ans: The linear data structure is a structure wherein data elements are adjacent to each other.

Examples of linear data structure include arrays, linked lists, stacks, and queues.

On the other hand, a non-linear data structure is a structure wherein each data element can connect to more than two adjacent data elements. Examples of nonlinear data structure include trees and graphs.

46. What is an AVL tree?

Ans: An AVL tree is a type of binary search tree that is always in a state of partially balanced. The balance is measured as a difference between the heights of the subtrees from the root. This self-balancing tree was known to be the first data structure to be designed as such.

47. What are doubly linked lists?

Ans: Doubly linked lists are a special type of linked list wherein traversal across the data elements can be done in both directions. This is made possible by having two links in every node, one that links to the next node and another one that connects to the previous node.

48. Briefly explain recursive algorithm.

Ans: Recursive algorithm targets a problem by dividing it into smaller, manageable sub-problems. The output of one recursion after processing one sub-problem becomes the input to the next recursive process.

49. How do you search for a target key in a linked list?

Ans: To find the target key in a linked list, you have to apply sequential search. Each node is traversed and compared with the target key, and if it is different, then it follows the link to the next node. This traversal continues until either the target key is found or if the last node is reached.



References:

1. https://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html

2. http://cooervo.github.io/Algorithms-DataStructures-BigONotation/

3. https://career.guru99.com/top-50-data-structure-interview-questions/

Sunday, September 17, 2017

Coin Change Problem: Dynamic Programming

package com.hackerrank.problems;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class CoinChange {

    static long getWays(long n, long[] c){
        // Complete this function
        Map<String,Long> m =  new HashMap<>();
        
        return change(n, c, 0, m);
    }
    
    static long change(long n, long[] c, int index, Map<String, Long> map){
        
        if(n == 0){
            return 1;
        }
        
        if(index >= c.length){
            return 0;
        }
        
        long ways = 0;
        
        long amountWithCoin = 0;
        
        String key = n + "-" + index; 
        System.out.println("Key" + key);
        
        if(map.containsKey(key)){
            return map.get(key);
        }
        
      
        while(amountWithCoin <= n){
            long remaining = n - amountWithCoin;
            ways = ways + change(remaining, c,index+1,map);
            amountWithCoin = amountWithCoin + c[index];
            System.out.println("Amount With Coin" + amountWithCoin);
        }
        map.put(key, ways);
        return ways;
    }

    public static void main(String[] args) {
        
        int n = 35;
        
        long[] c = {2, 5, 3, 6};
        
        long ways = getWays(n, c);
        
        System.out.println(ways);
    }

}

Monday, September 11, 2017

HashSet vs LinkedHashSet

**HashSet** uses buckets to store data which is stored in the form of array.

**LinkedHashSet** uses *doubly linked list* internally to store the data.

Now when the iteration happens in the HashSet the time depends on the `capacity` of the `HashSet`.

In case of LinkedHashSet it depends on the number of elements present in the set.

So even if the number of elements are lesser in the HashSet it might take more time because of the buckets. Hence iteration in LinkedHashSet is faster than HashSet.

From [grepcode][1]:

> Performance is likely to be just slightly below that of HashSet, due
> to the added expense of maintaining the linked list, with one
> exception: Iteration over a `LinkedHashSet` requires time proportional
> to the size of the set, regardless of its capacity.  
> Iteration over a HashSet is likely to be more expensive, requiring time proportional to
> its capacity. A **linked hash set** has two parameters that affect its
> performance: *initial capacity and load factor*. They are defined
> precisely as for `HashSet`. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are
> unaffected by capacity.


  [1]: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/util/LinkedHashSet.java/

Saturday, August 12, 2017

Merge LinkedList

Node mergeLists(Node headA, Node headB) {
     // This is a "method-only" submission.
     // You only need to complete this method
    Node currentA = headA;
    Node currentB = headB;
    Node mergedListHead = new Node();
    Node currentMerged = mergedListHead;
   
    while(currentA != null || currentB != null){
        if(currentA != null && currentB != null){
             if(currentA.data < currentB.data){
                currentMerged.next = currentA;
                currentA = currentA.next;
             }else{
                currentMerged.next = currentB;
                currentB = currentB.next;
             }
        }else if(currentB == null){
            currentMerged.next = currentA;
            break;
        }else if(currentA == null){
            currentMerged.next = currentB;
            break;
        }
        currentMerged = currentMerged.next;
    }
   
   return mergedListHead.next;

}

Wednesday, July 5, 2017

Check for Palindrome in JavaScript

Here is the code:

(function(){
'use strict';
var testStringOne = "Madam";
var testStringTwo = "testing";
var testNull = null;
var testUndefined;
console.log(checkIfPalindrome(testStringOne));
console.log(checkIfPalindrome(testStringTwo));
console.log(checkIfPalindrome(testNull));
console.log(checkIfPalindrome(testUndefined));
function checkIfPalindrome(testStringOne){
if(!testStringOne){
return false;
}
var testArrayOne = testStringOne.toLowerCase().split("");
testArrayOne.reverse();
if(testArrayOne.toString() == testStringOne.toLowerCase().split("").toString()){
return true;
}else{
return false;
}
}

})();