Showing posts with label data structures. Show all posts
Showing posts with label data structures. Show all posts

Sunday, May 12, 2019

How do you implement stack in java

Problem statement:
Stack data structure implementation in java.
  1. public class Stack {
  2.     static final int max = 15;
  3.     int top;
  4.     int a[] = new int[max];
  5.     boolean push(int x) {
  6.         if (top >= (max - 1)) {
  7.             System.out.println("stack overflow");
  8.             return false;
  9.         } else {
  10.             a[++top] = x;
  11.             System.out.println(x + " pushed into stack");
  12.             return true;
  13.         }
  14.     }
  15.     int pop() {
  16.         if (top < 0) {
  17.             System.out.println("stack underflow");
  18.             return 0;
  19.         } else {

  20.             int x = a[top--];
  21.             return x;
  22.         }
  23.     }
  24.     int size() {
  25.         return top + 1;
  26.     }
  27.     boolean isEmpty() {
  28.         return top == -1;
  29.     }
  30.     boolean isFull() {
  31.         return (top == (max - 1));
  32.     }
  33.     int peak() {
  34.         if (!isEmpty())
  35.             return a[top];
  36.         else return -1;
  37.     }
  38.     Stack() {
  39.         top = -1;
  40.     }
  41. }
  42. class MainExecution {
  43.     public static void main(String[] args) {
  44.         Stack s = new Stack();
  45.         s.push(10);
  46.         s.push(20);
  47.         s.push(30);
  48.         System.out.println("size: " + s.size());
  49.         s.push(25);
  50.         System.out.println("new size: " + s.size());
  51.         System.out.println(s.pop() + " popped from stack");
  52.         System.out.println("top element is peak: "+s.peak());
  53.     }
  54. }
Output:
10 pushed into stack
20 pushed into stack
30 pushed into stack
size: 3
25 pushed into stack
new size: 4
25 popped from stack
top element peak: 30

Friday, May 10, 2019

How to sort keys in TreeMap by using Comparator with user define objects?

Problem statement:
How to sort keys in TreeMap by using Comparator with user defined objects.
  1. import java.util.Comparator;
  2. import java.util.Set;
  3. import java.util.TreeMap;
  4. public class SortByKeyUserDefine {
  5.     public static void main(String a[]) {
  6.         //By using name comparator (String comparison)
  7.         System.out.println("========= Sort by name ==============");
  8.         TreeMap<Employee, String> tm = new TreeMap<Employee, String>(new MyNameComp());
  9.         tm.put(new Employee("Ram", 3000), "RAM");
  10.         tm.put(new Employee("John", 6000), "JOHN");
  11.         tm.put(new Employee("Crish", 2000), "CRISH");
  12.         tm.put(new Employee("Tom", 2400), "TOM");
  13.         Set<Employee> keys = tm.keySet();
  14.         for (Employee key : keys) {
  15.             System.out.println(key + " ==> " + tm.get(key));
  16.         }
  17.         System.out.println("========= Sort by salary ==============");
  18.         //By using salary comparator (int comparison)
  19.         TreeMap<Employee, String> trmap = new TreeMap<Employee, String>(new MySalaryComp());
  20.         trmap.put(new Employee("Ram", 3000), "RAM");
  21.         trmap.put(new Employee("John", 6000), "JOHN");
  22.         trmap.put(new Employee("Crish", 2000), "CRISH");
  23.         trmap.put(new Employee("Tom", 2400), "TOM");
  24.         Set<Employee> ks = trmap.keySet();
  25.         for (Employee key : ks) {
  26.             System.out.println(key + " ==> " + trmap.get(key));
  27.         }
  28.     }
  29. }

  30. class MyNameComp implements Comparator<Employee> {
  31.     @Override
  32.     public int compare(Employee e1, Employee e2) {
  33.         return e1.getName().compareTo(e2.getName());
  34.     }
  35. }

  36. class MySalaryComp implements Comparator<Employee> {
  37.     @Override
  38.     public int compare(Employee e1, Employee e2) {
  39.         if (e1.getSalary() > e2.getSalary()) {
  40.             return 1;
  41.         } else {
  42.             return -1;
  43.         }
  44.     }
  45. }

  46. class Employee {
  47.     private String name;
  48.     private int salary;
  49.     public Employee(String n, int s) {
  50.         this.name = n;
  51.         this.salary = s;
  52.     }
  53.     public String getName() {
  54.         return name;
  55.     }
  56.     public void setName(String name) {
  57.         this.name = name;
  58.     }
  59.     public int getSalary() {
  60.         return salary;
  61.     }
  62.     public void setSalary(int salary) {
  63.         this.salary = salary;
  64.     }
  65.     public String toString() {
  66.         return "Name: " + this.name + " , Salary: " + this.salary;
  67.     }
  68. }
Output:
========= Sort by name ==============
Name: Crish , Salary: 2000 ==> CRISH
Name: John , Salary: 6000 ==> JOHN
Name: Ram , Salary: 3000 ==> RAM
Name: Tom , Salary: 2400 ==> TOM
========= Sort by salary ==============
Name: Crish , Salary: 2000 ==> null
Name: Tom , Salary: 2400 ==> null
Name: Ram , Salary: 3000 ==> null
Name: John , Salary: 6000 ==> null

How do you sort alphanumeric key of a map OR Sort map by key in java?

Problem statement:
How do you sort alphanumeric key of a map ?

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import java.util.TreeMap;
  5. public class SortAlphanumericKeyInMap {
  6.     public static void main(String[] args) {
  7.         Map<String, String> map = new HashMap<>();
  8.         map.put("A1BB", "1");
  9.         map.put("A2CC", "2");
  10.         map.put("A2AA", "2");
  11.         map.put("B1AA", "7");
  12.         Map<String, String> treeMap = new TreeMap<>(map);
  13.         Set<String> keys = treeMap.keySet();
  14.         for (String key : keys) {
  15.             System.out.println(key);
  16.         }
  17.     }
  18. }
Output:
A1BB
A2AA

A2CC
B1AA

Wednesday, April 3, 2019

Two Sum [find a pair of index or two sum of index in a list]

Problem statement:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

import java.util.HashMap;
public class Solutions {
    public static void main(String args[]) {
        int nums[] = {2, 7, 11, 15};
        int target = 9;
        int idx[] = twoSum(nums, target);
        for (int index : idx) {
            System.out.print(index + " ");
        }
    }

    public static int[] twoSum(int nums[], int target) {
        HashMap m = new HashMap();
        int arr[] = new int[2];

        for (int i = 0; i < nums.length; i++) {
            Integer val = (Integer) m.get(target - nums[i]);
            if (val == null) {
                m.put(nums[i], i);
            } else {
                arr[0] = val;
                arr[1] = i;
            }
        }
        return arr;
    }
}
Output:    [0,1]
Expected: [0,1]

Friday, October 12, 2018

How do you remove the special characters from a string using Regex in java ?

Problem statement:
can you remove the special character from a string using regex in java?

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemoveSpecialCharacter{
      public static void main(String args[]){
      String c = "p$82-a/*@#^&873";
     
      Pattern pt = Pattern.compile("^a-zA-Z0-9");
      Matcher match = pt.matcher(c);
      while(match.find()){
        String s = match.group();
        c = c.replaceAll("\\"+s, "");
       }
        System.out.println(c);
      }
}
Output:
p82a873

Wednesday, October 3, 2018

What are the applications of Topological Sorting in graph?

Problem statement: 
what are the uses of Topological Sorting in graph?
  1. Representing course prerequisites
  2. In detecting deadlocks
  3. Evaluating formulae in spreadsheet
  4. Pipeline of computing jobs
  5. Checking for symbolic link loop

What do you mean by Topological Sort in graph ?

Problem statement: 
what is Topological sort in graph data structure & algorithm?

Topological sort is an ordering of vertices in a directed acyclic  graph [DAG] in which each node comes before all nodes to which it has outgoing edges.
For example:
Consider the course prerequisite structure at universities. A directed edge (v,w) indicates that course v must be completed before course w. Every DAG may have one or more topological orderings. Topological sort is not possible if the graph has a cycle, since for two vertices v & w on the cycle, v precedes w & w precedes v.

Monday, July 16, 2018

Problem statement:
There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neighbour). Each day, for each cell, if its neighbours are both active or both inactive, the cell becomes inactive the next day,. otherwise it becomes active the next day.

Assumptions: The two cells on the ends have single adjacent cell, so the other adjacent cell can be assumsed to be always inactive. Even after updating the cell state. consider its pervious state for updating the state of other cells. Update the cell informationof allcells simultaneously.

Write a fuction cellCompete which takes takes one 8 element array of integers cells representing the current state of 8 cells and one integer days representing te number of days to simulate. An integer value of 1 represents an active cell and value of 0 represents an inactive cell.

TESTCASES 1:
INPUT:
[1,0,0,0,0,1,0,0],1
EXPECTED RETURN VALUE:
[0,1,0,0,1,0,1,0]

TESTCASE 2:
INPUT:
[1,1,1,0,1,1,1,1,],2
EXPECTED RETURN VALUE:
[0,0,0,0,0,1,1,0]


public class Colony {

    public static int[] cellCompete(int[] cells, int days) {

        int len = cells.length;
        int[] newCells = new int[cells.length];
        for (int k = 0; k < days; k++) {
            for (int i = 0; i < cells.length; i++) {
                int cell = cells[i];
                int nextCell;
                int prevCell;
                int activenumber;
                if (i == 0) {
                    // edge cases
                    nextCell = cells[1];
                    prevCell = 0;
                } else if (i == cells.length - 1) {
                    // edge case
                    prevCell = cells[cells.length - 2];
                    nextCell = 0;
                } else {
                    nextCell = cells[i + 1];
                    prevCell = cells[i - 1];
                }
                if (nextCell == prevCell) {
                    // set it to inactive
                    activenumber = 0;
                } else {
                    //set it to active
                    activenumber = 1;
                }
                newCells[i] = activenumber;
            }
            for (int i = 0; i < 8; i++) {
                cells[i] = newCells[i];
            }
        }
        return newCells;
    }
    public static void main(String[] args) {
        int[] array = {1, 1, 1, 0, 1, 1, 1, 1};
        int days = 2;
        array = cellCompete(array, days);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
    }
}

How do you calculate Cube Root of a number in Java?

Problem statement: Find the cube root of a number in java.
public class CubeRootExe {
    public static void main(String args[]) {
        double cbRt = cubeRoot(8);
        System.out.println(cbRt);
    }
    public static double cubeRoot(double n) {
        return Math.cbrt(n);
    }
}
Output:
2.0

How do you write an algorithm for the multiplication of two matrix [2D array]?

Problem statement:
Given two matrices, the task is to multiply them. Matrices can either be square or rectangular.
Example:
Input: int m1[][] = {{2, 3, 4}, {5, 6, 7}}; // 2 X 3 matrix
int m2[][] = {{1, 2}, {3, 4}, {5, 6}}; // 3 X 2 matrix
Output: {{31, 40},{58,76}}
  1. public class MatrixMultiplication {
  2.     public static void main(String args[]) {
  3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
  4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
  5.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
  6.         for (int i = 0; i < 2; i++) {   // i represent row
  7.             for (int j = 0; j < 2; j++) {   // j represent column
  8.                 res[i][j] = 0;  // assume res[0][0] = 0
  9.                 for (int k = 0; k < 3; k++) {
  10.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
  11.                     res[i][j] = res[i][j] + m1[i][k] * m2[k][j];
  12.                 }
  13.             }
  14.         }
  15.         // printing the resultant matrix
  16.         for (int i = 0; i < 2; i++) {
  17.             for (int j = 0; j < 2; j++) {
  18.                 System.out.print(res[i][j] + " ");
  19.             }
  20.             System.out.println();
  21.         }
  22.     }
  23. }
Method-II:
  1. public class MatrixMultiplication2D {
  2.     public static void main(String args[]) {
  3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
  4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
  5.         int sum = 0;    // initial sum value is 0
  6.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
  7.         for (int i = 0; i < 2; i++) {   // i represent row
  8.             for (int j = 0; j < 2; j++) {   // j represent column
  9.                 res[i][j] = 0;  // assume res[0][0] = 0
  10.                 for (int k = 0; k < 3; k++) {
  11.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
  12.                     sum = sum + m1[i][k] * m2[k][j];
  13.                 }
  14.                 res[i][j] = sum;    //  assigned sum value to resultant matrix
  15.                 sum = 0;    // reset to 0 for next iteration
  16.             }
  17.         }
  18.         // printing the resultant matrix
  19.         for (int i = 0; i < 2; i++) {
  20.             for (int j = 0; j < 2; j++) {
  21.                 System.out.print(res[i][j] + " ");
  22.             }
  23.             System.out.println();
  24.         }
  25.     }
  26. }
Output:
31 40
58 76

Sunday, July 15, 2018

What will be the output of overriding concept?

Problem statement: what will be the output of the below code?
class C{
    public void run(int a){
        System.out.println("int: "+a);
    }
    public void run(long a){
        System.out.println("long");
    }
}
public class DemoSample1 {
    public static void main(String args[]){
        C c = new C();
        c.run('a');
    }
}
Output:
int: 97

Friday, July 13, 2018

Fibonacci Number

Problem statement:
Given a number n, print n-th Fibonacci Number.
Input : n = 2 
Output : 1 
Input : n = 9 
Output : 34
public class FibonacciSeries {
    static int fib(int n) {
        if (n <= 1)
            return n;
        return fib(n - 1) + fib(n - 2);
    }
    public static void main(String args[]) {
        int n = 9;
        System.out.println(fib(n));
    }
}
Output:
34

Fibonacci Numbers

Problem statement:

Program to print first n Fibonacci Numbers


public class Test {
    // Method to print first n Fibonacci Numbers    static void printFibonacciNumbers(int n) {
        int f1 = 0, f2 = 1, i;
        if (n < 1)
            return;
        for (i = 1; i <= n; i++) {
            System.out.print(f2 + " ");
            int next = f1 + f2;
            f1 = f2;
            f2 = next;
        }
    }
    public static void main(String[] args) {
        printFibonacciNumbers(7);
    }
}
Output:
1 1 2 3 5 8 13

How do I increment each character in a string using Java?

Problem statement:
You will be given a sentence from from english language. Your job is to increment the letters of the string by an offset of 1. The increment shall be done in a cyclic order i.e. replacement will be as follows:

'a' replaced by 'b', 'b' replaced by 'c' ............. 'z' replaced by 'a'


Method-I:
public class IncrementLetterOfWord {
    public static void main(String args[]) {
        String str = "ABCDEF";
        String res = "";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            res = res + (char) (c + 1);
        }
        System.out.println(res);
    }
}
Method-II:
public class IncrementLetterByOne {
    public static void main(String args[]) {
        String str = "ABCDEF";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            sb.append((char) (str.charAt(i) + 1));
        }
        System.out.println(sb);
    }
}
Output:
BCDEFG

How do write an algorithm to print prime number ?

Problem statement:
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.

Example:

Input : n =10 
Output : 2 3 5 7 
Input : n = 20 
Output: 2 3 5 7 11 13 17 19
  1. public class PrimeNumberSeries {
  2.     public static void main(String arg[]) {
  3.         primeNumberSeries(10);
  4.     }
  5.     public static void primeNumberSeries(int n) {
  6.         // Create a boolean array "prime[0..n]" and initialize all entries it as            //true. A value in prime[i] will finally be false if i is Not a prime, else true
  7.         boolean prime[] = new boolean[n + 1];
  8.         for (int i = 0; i < n; i++) {
  9.             prime[i] = true;
  10.         }
  11.         for (int p = 2; p * p <= n; p++) {
  12.             if (prime[p] == true) {
  13.                 // update all multiple of p
  14.                 for (int i = p * 2; i <= n; i = i + p) {
  15.                     prime[i] = false;
  16.                 }
  17.             }
  18.         }
  19.         // print all prime numbers
  20.         for (int i = 2; i <= n; i++) {
  21.             if (prime[i] == true) {
  22.                 System.out.print(i + " ");
  23.             }
  24.         }
  25.     }
  26. }
output:
2 3 5 7 

Wednesday, July 4, 2018

Poisonous Plants

There are a number of plants in a garden. Each of these plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies.
You are given the initial values of the pesticide in each of the plants. Print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.
For example, pesticide levels . Using a -indexed array, day  plants  and  die leaving . On day , plant  of the current array dies leaving . As there is no plant with a higher concentration of pesticide than the one to its left, plants stop dying after day .
Function Description Complete the function poisonousPlants in the editor below. It must return an integer representing the number of days until plants no longer die from pesticide.
poisonousPlants has the following parameter(s):
  • p: an array of integers representing pesticide levels in each plant
Input Format
The first line contains an integer , the size of the array .
The next line contains  space-separated integers .
Constraints
Output Format
Output an integer equal to the number of days after which no plants die.
Sample Input
7
6  5  8  4  7  10  9
Sample Output
2
Explanation
Initially all plants are alive.
Plants = {(6,1), (5,2), (8,3), (4,4), (7,5), (10,6), (9,7)}
Plants[k] = (i,j) => jth plant has pesticide amount = i.
After the 1st day, 4 plants remain as plants 3, 5, and 6 die.
Plants = {(6,1), (5,2), (4,4), (9,7)}
After the 2nd day, 3 plants survive as plant 7 dies.
Plants = {(6,1), (5,2), (4,4)}
After the 2nd day the plants stop dying.

import java.util.Scanner;
import java.util.Stack;
public class PP {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int[] ar = new int[sc.nextInt()];
        for (int i = 0; i < ar.length; i++) {
            ar[i] = sc.nextInt();
        }
        Stack<Integer> st = new Stack<Integer>();
        int i = ar.length - 1;
        boolean day1 = false;
        int maxsize = 0, minsize = 0, days = 0;
        while (i >= 0) {
            while (i > 0 && ar[i] > ar[i - 1]) {
                i--;
                day1 = true;
            }
            // TODO Setup your maxsize and minsize            
            while (st.size() > 0 && ar[i] < st.peek())
                st.pop();
            // TODO Calc days            
            st.push(ar[i--]);
        }
        System.out.println(days + (day1 ? 1 : 0));
    }
}
ref:https://www.hackerrank.com/challenges/poisonous-plants/problem

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...