Thursday, 10 August 2017

CTCI Challange, DAY 12

Day 12:- 

Problem Statement:-Merge Sort: Counting Inversions

practiced the mergesort before going to solve the problem,It was very easy.

Solution:-

public class Inversions {

    static long countInversions(int[] arr) {
        MergeSort mr = new MergeSort();
        return mr.mergesort(arr);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int a0 = 0; a0 < t; a0++) {
            int n = in.nextInt();
            int[] arr = new int[n];
            for (int arr_i = 0; arr_i < n; arr_i++) {
                arr[arr_i] = in.nextInt();
            }
            long result = countInversions(arr);
            System.out.println(result);
        }
        in.close();
    }

    private static long merge(int[] a, int[] aux, int lo, int mid, int hi) {
        long inversions = 0;

        // copy to aux[]
        for (int k = lo; k <= hi; k++) {
            aux[k] = a[k];
        }

        // merge back to a[]
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; k++) {
            if (i > mid) a[k] = aux[j++];
            else if (j > hi) a[k] = aux[i++];
            else if (aux[j] < aux[i]) {
                a[k] = aux[j++];
                inversions += (mid - i + 1);
            } else a[k] = aux[i++];
        }
        return inversions;
    }

}

class MergeSort {

    public long mergesort(int[] array) {
        int[] helper = new int[array.length];
        return mergesort(array, helper, 0, array.length - 1);
    }

    public long mergesort(int[] array, int[] helper, int low, int high) {
        long count = 0;
        if (low < high) {
            int middle = (low + high) / 2;
            count += mergesort(array, helper, low, middle); // Sort left half
            count += mergesort(array, helper, middle + 1, high); // Sort right half
            count += merge(array, helper, low, middle, high); // Merge them
        }
        return count;
    }

    /*public long merge(int[] array, int[] helper, int low, int middle, int high) {

*//* Copy both halves into a helper array *//*
        for (int i = low; i <= high; i++) {
            helper[i] = array[i];
        }

        int helperLeft = low;
        int helperRight = middle + 1;
        int current = low;

*//* Iterate through helper array. Compare the left and right
         * half, copying back the smaller element from the two halves
* into the original array. *//*
        while (helperLeft <= middle && helperRight <= high) {
            if (helper[helperLeft] <= helper[helperRight]) {
                array[current] = helper[helperLeft];
                helperLeft++;
            } else { // If right element is smaller than left element
                array[current] = helper[helperRight];
                helperRight++;
                count++;
            }
            current++;
        }

*//* Copy the rest of the left side of the array into the
         * target array *//*

        int remaining = middle - helperLeft;
        count += remaining;
        for (int i = 0; i <= remaining; i++) {
            array[current + i] = helper[helperLeft + i];
        }
        int remaining1 = high - helperRight;
        for (int i = 0; i <= remaining1; i++) {
            array[current + i] = helper[helperLeft + i];
        }
        return count;
    }*/

    private static long merge(int[] a, int[] aux, int lo, int mid, int hi) {
        long inversions = 0;
        // copy to aux[]
        for (int k = lo; k <= hi; k++) {
            aux[k] = a[k];
        }

        // merge back to a[]
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; k++) {
            if (i > mid) a[k] = aux[j++];
            else if (j > hi) a[k] = aux[i++];
            else if (aux[j] < aux[i]) {
                a[k] = aux[j++];
                inversions += (mid - i + 1);
            } else a[k] = aux[i++];
        }
        return inversions;
    }
}

Thursday, 3 August 2017

NOTE:- CTCI Challange

I wont be working on this weekend(5th and 6th august) as I will be busy in family function.

Note:-on 10th Aug,2 days gap extended to 7 days,Sorry.

CTCI Challange, DAY 11

Day 11

Problem Statement:- Sorting: Comparator

Today's problem was very easy,on comparators.
i have copied the int to Integer so as to use the compareTo() functionality.

On Paper:-




Solution:-

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Player {
    String name;
    int score;

    Player(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

class Checker implements Comparator<Player> {

    @Override    public int compare(Player o1, Player o2) {
        Integer i1 = o1.score;
        Integer i2 = o2.score;
        if (i2.compareTo(i1) == 0) {
            return o1.name.compareTo(o2.name);
        }
        return i2.compareTo(i1);
    }
}

class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        Player[] player = new Player[n];
        Checker checker = new Checker();

        for (int i = 0; i < n; i++) {
            player[i] = new Player(scan.next(), scan.nextInt());
        }
        scan.close();

        Arrays.sort(player, checker);
        for (int i = 0; i < player.length; i++) {
            System.out.printf("%s %s\n", player[i].name, player[i].score);
        }
    }
}

Wednesday, 2 August 2017

CTCI Challange, DAY 10

Day 10:-

Problem Statement:-Sorting: Bubble Sort

The problem is an implementation of bubble sort,it was very easy.
did very silly mistake,need to be concious.

import java.util.Scanner;

/**
 * @author vikram.shanbogar@gmail.com
 * on 8/3/2017.
 */
public class Bsort {
    static int swaps = 0;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long a[] = new long[n];
        for (int a_i = 0; a_i < n; a_i++) {
            a[a_i] = in.nextInt();
        }
        sort(a);
        printOutputs(a);
    }

    private static void printOutputs(long[] a) {
        System.out.printf("Array is sorted in %d swaps.\n", swaps);
        if (a.length > 0) {
            System.out.printf("First Element: %d\n", a[0]);
            System.out.printf("Last Element: %d", a[a.length - 1]);
        }
    }

    private static void sort(long[] a) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length-1; j++) {
                if (a[j] > a[j+1]) {
                    exch(a, j, j+1);
                    swaps++;
                }
            }
        }
    }

    private static void exch(long[] pq, int i, int j) {
        long swap = pq[i];
        pq[i] = pq[j];
        pq[j] = swap;
    }
}

CTCI Challange, DAY 9

Day 9:- 
Problem statement:- Tries: Contacts

Note:-
Updated version below..
 
Tries is new concept,I gone through the Princeton algorithms lectures and got a picture of what this data structure is all about.

Implemented the logic using the existing algorithms given by Princeton.

import java.util.*;

/**
 * @author vikram.shanbogar@gmail.com
 * on 8/2/2017.
 */
public class Tries<Value> {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        TrieST<Integer> tries = new TrieST();
        List<Integer> list = new ArrayList<>();
        for (int a0 = 0; a0 < n; a0++) {
            String op = in.next();
            String contact = in.next();
            if (op.equals("add")) {
                tries.put(contact, a0);
            }
            if (op.equals("find")) {
                int count = 0;
                for (Object s : tries.keysWithPrefix(contact))
                    count++;
                System.out.println(count);
            }
        }
    }

    public static class TrieST<Value> {
        private static final int R = 256;        // extended ASCII


        private Node root;      // root of trie
        private int n;          // number of keys in trie

        // R-way trie node
        private static class Node {
            private Object val;
            private Node[] next = new Node[R];
        }

        /**
         * Initializes an empty string symbol table.
         */
        public TrieST() {
        }


        /**
         * Returns the value associated with the given key.
         *
         * @param key the key
         * @return the value associated with the given key if the key is in the symbol table
         * and {@code null} if the key is not in the symbol table
         * @throws IllegalArgumentException if {@code key} is {@code null}
         */
        public Value get(String key) {
            if (key == null) throw new IllegalArgumentException("argument to get() is null");
            Node x = get(root, key, 0);
            if (x == null) return null;
            return (Value) x.val;
        }

        /**
         * Does this symbol table contain the given key?
         *
         * @param key the key
         * @return {@code true} if this symbol table contains {@code key} and
         * {@code false} otherwise
         * @throws IllegalArgumentException if {@code key} is {@code null}
         */
        public boolean contains(String key) {
            if (key == null) throw new IllegalArgumentException("argument to contains() is null");
            return get(key) != null;
        }

        private Node get(Node x, String key, int d) {
            if (x == null) return null;
            if (d == key.length()) return x;
            char c = key.charAt(d);
            return get(x.next[c], key, d + 1);
        }

        /**
         * Inserts the key-value pair into the symbol table, overwriting the old value
         * with the new value if the key is already in the symbol table.
         * If the value is {@code null}, this effectively deletes the key from the symbol table.
         *
         * @param key the key
         * @param val the value
         * @throws IllegalArgumentException if {@code key} is {@code null}
         */
        public void put(String key, Value val) {
            if (key == null) throw new IllegalArgumentException("first argument to put() is null");
            if (val == null) delete(key);
            else root = put(root, key, val, 0);
        }

        private Node put(Node x, String key, Value val, int d) {
            if (x == null) x = new Node();
            if (d == key.length()) {
                if (x.val == null) n++;
                x.val = val;
                return x;
            }
            char c = key.charAt(d);
            x.next[c] = put(x.next[c], key, val, d + 1);
            return x;
        }

        /**
         * Returns the number of key-value pairs in this symbol table.
         *
         * @return the number of key-value pairs in this symbol table
         */
        public int size() {
            return n;
        }

        /**
         * Is this symbol table empty?
         *
         * @return {@code true} if this symbol table is empty and {@code false} otherwise
         */
        public boolean isEmpty() {
            return size() == 0;
        }

        /**
         * Returns all keys in the symbol table as an {@code Iterable}.
         * To iterate over all of the keys in the symbol table named {@code st},
         * use the foreach notation: {@code for (Key key : st.keys())}.
         *
         * @return all keys in the symbol table as an {@code Iterable}
         */
        public Iterable<String> keys() {
            return keysWithPrefix("");
        }

        /**
         * Returns all of the keys in the set that start with {@code prefix}.
         *
         * @param prefix the prefix
         * @return all of the keys in the set that start with {@code prefix},
         * as an iterable
         */
        public Iterable<String> keysWithPrefix(String prefix) {
            Queue<String> results = new PriorityQueue<>();
            Node x = get(root, prefix, 0);
            collect(x, new StringBuilder(prefix), results);
            return results;
        }

        private void collect(Node x, StringBuilder prefix, Queue<String> results) {
            if (x == null) return;
            if (x.val != null) results.offer(prefix.toString());
            for (char c = 0; c < R; c++) {
                prefix.append(c);
                collect(x.next[c], prefix, results);
                prefix.deleteCharAt(prefix.length() - 1);
            }
        }

        /**
         * Returns all of the keys in the symbol table that match {@code pattern},
         * where . symbol is treated as a wildcard character.
         *
         * @param pattern the pattern
         * @return all of the keys in the symbol table that match {@code pattern},
         * as an iterable, where . is treated as a wildcard character.
         */
        public Iterable<String> keysThatMatch(String pattern) {
            Queue<String> results = new PriorityQueue<>();
            collect(root, new StringBuilder(), pattern, results);
            return results;
        }

        private void collect(Node x, StringBuilder prefix, String pattern, Queue<String> results) {
            if (x == null) return;
            int d = prefix.length();
            if (d == pattern.length() && x.val != null)
                results.offer(prefix.toString());
            if (d == pattern.length())
                return;
            char c = pattern.charAt(d);
            if (c == '.') {
                for (char ch = 0; ch < R; ch++) {
                    prefix.append(ch);
                    collect(x.next[ch], prefix, pattern, results);
                    prefix.deleteCharAt(prefix.length() - 1);
                }
            } else {
                prefix.append(c);
                collect(x.next[c], prefix, pattern, results);
                prefix.deleteCharAt(prefix.length() - 1);
            }
        }

        /**
         * Returns the string in the symbol table that is the longest prefix of {@code query},
         * or {@code null}, if no such string.
         *
         * @param query the query string
         * @return the string in the symbol table that is the longest prefix of {@code query},
         * or {@code null} if no such string
         * @throws IllegalArgumentException if {@code query} is {@code null}
         */
        public String longestPrefixOf(String query) {
            if (query == null) throw new IllegalArgumentException("argument to longestPrefixOf() is null");
            int length = longestPrefixOf(root, query, 0, -1);
            if (length == -1) return null;
            else return query.substring(0, length);
        }

        // returns the length of the longest string key in the subtrie
        // rooted at x that is a prefix of the query string,
        // assuming the first d character match and we have already
        // found a prefix match of given length (-1 if no such match)
        private int longestPrefixOf(Node x, String query, int d, int length) {
            if (x == null) return length;
            if (x.val != null) length = d;
            if (d == query.length()) return length;
            char c = query.charAt(d);
            return longestPrefixOf(x.next[c], query, d + 1, length);
        }

        /**
         * Removes the key from the set if the key is present.
         *
         * @param key the key
         * @throws IllegalArgumentException if {@code key} is {@code null}
         */
        public void delete(String key) {
            if (key == null) throw new IllegalArgumentException("argument to delete() is null");
            root = delete(root, key, 0);
        }

        private Node delete(Node x, String key, int d) {
            if (x == null) return null;
            if (d == key.length()) {
                if (x.val != null) n--;
                x.val = null;
            } else {
                char c = key.charAt(d);
                x.next[c] = delete(x.next[c], key, d + 1);
            }

            // remove subtrie rooted at x if it is completely empty
            if (x.val != null) return x;
            for (int c = 0; c < R; c++)
                if (x.next[c] != null)
                    return x;
            return null;
        }
    }
}

Note:- updated on 22/8/17
Today got time to work on CTCI backlogs.Completed the tries problem.

package vikram.HR;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class TrieNode1 {
    char c;
    HashMap<Character, TrieNode1> children = 
            new HashMap<Character, TrieNode1>();
    boolean isLeaf;
    public int size;

    public TrieNode1() {
    }

    public TrieNode1(char c) {
        this.c = c;
    }
}

class Trie {
    private TrieNode1 root = new TrieNode1();

    public void insert(String word) {
        HashMap<Character, TrieNode1> children = root.children;

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);

            TrieNode1 t;
            if (children.containsKey(c)) {
                t = children.get(c);
            } else {
                t = new TrieNode1(c);
                children.put(c, t);
            }

            children = t.children;

            //set leaf node            if (i == word.length() - 1)
                t.isLeaf = true;
            t.size++;
        }
    }

    // Returns if the word is in the trie.    
public boolean search(String word) {
        TrieNode1 t = searchNode(word);

        if (t != null && t.isLeaf)
            return true;
        else            return false;
    }

    // Returns if there is any word in the trie    
// that starts with the given prefix.   
       public int startsWith(String prefix) {
        TrieNode1 val = searchNode(prefix);
        if (val == null)
            return 0;
        else            return val.size;
    }

    public TrieNode1 searchNode(String str) {
        Map<Character, TrieNode1> children = 
                root.children;
        TrieNode1 t = null;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (children.containsKey(c)) {
                t = children.get(c);
                children = t.children;
            } else {
                return null;
            }
        }

        return t;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Trie t = new Trie();
        for (int a0 = 0; a0 < n; a0++) {
            String op = in.next();
            String contact = in.next();
            if (op.equals("add")) {
                t.insert(contact);
            } else {
                System.out.println(t.startsWith(contact));
            }
        }
    }
}

CTCI Challange, DAY 8

Day 8:- 

Problem statement:- Heaps: Find the Running Median

I have studied a lot on heaps,but this is the first implementation by me.

Thought the problem is very easy,but solving with time constraint using heaps priority queues was very time consuming.
I implemented it using heapsort.

On paper:-





import java.util.Arrays;
import java.util.Scanner;

/**
 * @author vikram.shanbogar@gmail.com
 * on 8/2/2017.
 */
public class Heaps {
    static int index;
    static int[] a;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        a = new int[n];
        for (int a_i = 0; a_i < n; a_i++) {
            //a[a_i] = in.nextInt();
            index = a_i;
            insert(in.nextInt());
        }
    }

    private static void insert(int data) {
        a[index] = data;
        if (index == 0) {
            System.out.printf("%.1f\n", (float) a[index]);
            return;
        }
        sort(a);
        calcMedian(a);
    }

    private static void calcMedian(int[] temp) {
        float median;
        int x = index + 1;
        if (x % 2 == 0)
            median = (float) (temp[(x / 2)] + temp[(x / 2) - 1]) / 2;
        else
            median = (float) temp[(x / 2)];
        System.out.printf("%.1f\n", median);
    }

    public static int[] sort(int[] pq) {
        int n = index + 1;
        for (int k = n / 2; k >= 1; k--)
            sink(pq, k, n);
        while (n > 1) {
            exch(pq, 1, n--);
            sink(pq, 1, n);
        }
        return pq;
    }

    private static void sink(int[] pq, int k, int n) {
        while (2 * k <= n) {
            int j = 2 * k;
            if (j < n && less(pq, j, j + 1)) j++;
            if (!less(pq, k, j)) break;
            exch(pq, k, j);
            k = j;
        }
    }

    private static boolean less(int[] pq, int i, int j) {
        return (pq[i - 1] < (pq[j - 1]));
    }

    private static void exch(int[] pq, int i, int j) {
        int swap = pq[i - 1];
        pq[i - 1] = pq[j - 1];
        pq[j - 1] = swap;
    }
}


Note:-
Updated on 18th Aug.
tried with new approach as few of the test cases were not running with the above solution.

import edu.princeton.cs.algs4.MaxPQ;
import edu.princeton.cs.algs4.MinPQ;

import java.util.*;

/** * @author vikram.shanbogar@gmail.com * on 8/2/2017. */
public class Heaps2 {
    static int index;
    static int[] a;

    static Queue<Integer> leftQueue = new PriorityQueue<>
            (Collections.reverseOrder());
    static Queue<Integer> rightQueue = new PriorityQueue<>();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        for (int a_i = 0; a_i < n; a_i++) {
            index = a_i;
            //insert(in.nextInt());           
            int val = in.nextInt();
            insert(val);
            System.out.println(calcMedian());
        }
    }

    private static void insert(int val) {
        Queue q;
        if (leftQueue.size() <= rightQueue.size()) {
            q = leftQueue;
        } else            q = rightQueue;
        q.add(val);
        if (!leftQueue.isEmpty() && !rightQueue.isEmpty() 
                && leftQueue.peek() > rightQueue.peek()) {
            int left = leftQueue.poll();
            int right = rightQueue.poll();
            leftQueue.add(right);
            rightQueue.add(left);
        }
    }

    private static float calcMedian() {
        if (leftQueue.size() == rightQueue.size()) {
            return (float) (leftQueue.peek() + rightQueue.peek()) / 2;
        } else            
         return leftQueue.peek();
    }
}

Tuesday, 1 August 2017

CTCI Challange, DAY 7

Day 7:-
I missed 1 day as i was busy in other stuff.

Problen Statement:- Is This a Binary Search Tree?

My approach:-

  • First i solved BinaryTree logic completely.
  • then i started with inorder traversal to check for BST correctness with left less than root and right greater than root.
  • Used set to check for duplicates.

On Paper:-





package vikram.CTCI;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author vikram.shanbogar@gmail.com
 * on 7/31/2017.
 */
public class BinaryTree {

    //  The Node class is defined as follows:
    static class Node {
        int data;
        Node left;
        Node right;

        Node(int data) {
            this.data = data;
        }
    }

    List<Integer> list = new ArrayList<>();
    int counts = 1;
    Node root;
    boolean isBST = true;

    private boolean inorder(Node root) {

        if (root.left != null) {
            if (root.left.data >= root.data) {
                isBST = false;
            }
            counts++;
            inorder(root.left);
        }
        if (list.size() > 0 && root.data <= list.get(list.size() - 1)) {
            isBST = false;
        }
        list.add(root.data);
        //System.out.print(root.data + " ");
        if (root.right != null) {
            if (root.right.data <= root.data) {
                isBST = false;
            }
            counts++;
            inorder(root.right);
        }
        return isBST;
    }

    public void inorder() {
        inorder(root);
    }

    public void insert(int data) {
        if (root == null) {
            root = new Node(data);
            return;
        } else
            insert(root, data);
    }

    public void insert(Node root, int data) {
        if (data < root.data) {
            if (root.left == null) {
                root.left = new Node(data);
                return;
            } else
                insert(root.left, data);
        }
        if (data > root.data) {
            if (root.right == null) {
                root.right = new Node(data);
                return;
            } else
                insert(root.right, data);
        }
    }

    public boolean checkBST(Node root) {
        inorder(root);
        if (new LinkedHashSet<>(list).size() < counts) {
            isBST = false;
        }
        System.out.println(isBST);
        return false;
    }
}

Improvements:-
Took more time than i thought.

Learnings:-
I learned more about inner classes,junit which was pending for a long time.

Installing Docker and Minikube

  install docker-   sudo apt install docker.io   set user to docker group:- sudo gpasswd -a   {user} docker   imp commands:- ...