Showing posts with label Interview Programs. Show all posts
Showing posts with label Interview Programs. Show all posts

Friday, 23 November 2018

  • Need to remove common number 4 from both arrays
  • Input
    • int[] arr1 = { 1, 4, 6, 7, 8 };
    • int[] arr2 = { 2, 4, 5, 9, 0 };
  • Output
    • int[] arr1 = { 1, 6, 7, 8 };
    • int[] arr2 = { 2, 5, 9, 0 };
  • RemoveCommonElements.java
  • public class RemoveCommonElements { public static void main(String[] args) { RemoveCommonElements app = new RemoveCommonElements(); app.commonRemove(); } private void commonRemove() { int[] arr1 = { 1, 4, 6, 7, 8 }; int[] arr2 = { 2, 4, 5, 9, 0 }; for (int e : arr1) { if (contains(arr2, e)) { remove(arr1, e); remove(arr2, e); } } System.out.print(arr1); System.out.print(arr2); } private boolean contains(int[] arr, int e) { for (int i : arr) { if (i == e) { return true; } } return false; } private int[] remove(int[] arr, int e) { for (int i = 0; i < arr.length; i++) { if (arr[i] == e) { for (int j = i; j < arr.length-1; j++) { arr[j] = arr[j + 1]; } } } return arr; } } ######### RESULT ########## 1, 6, 7, 8, 8 2, 5, 9, 0 ,0
  • In below example CopyOnWriteArrayList will be concurrent in type and ConcurrentModificationException can be prevent
  • /** * Get UNION list * Get INTERSECTION LIST by retainAll //common elements * Remove intersection from union */ private static void removeCommonElements() { List list1 = Arrays.asList(1, 2, 3, 4, 5, 6); List list2 = Arrays.asList(10, 2, 3, 40, 50, 60); List union = new ArrayList(list1); union.addAll(list2); List intersection = new ArrayList<>(list1); // only common elements intersection.retainAll(list2); union.removeAll(intersection); System.out.println(union); }

Monday, 22 October 2018


  • Create shared Semaphore object , lock and unlock in consumer - producer  blocks by limiting thread accessible count to 1
  • Output will be like produce 1 and consume 1 , produce 2 and consume 2 ...
  • Producer.java
    • public class Producer implements Runnable { private static List LIST; private static Semaphore semaphore; public Producer(List LISTv, Semaphore semaphoreV) { LIST = LISTv; semaphore = semaphoreV; } public void run() { produce(); } private static void produce() { try { int i = 1; while (true) { semaphore.acquire(); LIST.add(i); System.out.println(i + " Produced"); i++; semaphore.release(); if (i > 100) { break; } } } catch (Exception e) { e.printStackTrace(); } } }
  • Consumer.java
    • public class Consumer implements Runnable { private static List LIST; private static Semaphore semaphore; public Consumer(List LISTv, Semaphore semaphoreV) { LIST = LISTv; semaphore = semaphoreV; } public void run() { consume(); } private static void consume() { int index = 0; try { while (true) { semaphore.acquire(); index = LIST.size() - 1; System.out.println(LIST.get(index) + " Removed"); LIST.remove(index); semaphore.release(); } } catch (Exception e) { e.printStackTrace(); } } }
  • App.java
    • public class App { private static List LIST = new ArrayList(); private static Semaphore SEMAPHORE = new Semaphore(1, true); public static void main(String[] args) { Thread producer = new Thread(new Producer(LIST, SEMAPHORE)); Thread consumer = new Thread(new Consumer(LIST, SEMAPHORE)); producer.start(); consumer.start(); } }
  • Output
    • 1 Produced 1 Removed 2 Produced 2 Removed 3 Produced 3 Removed 4 Produced 4 Removed 5 Produced 5 Removed 6 Produced 6 Removed 7 Produced 7 Removed 8 Produced 8 Removed 9 Produced 9 Removed 10 Produced 10 Removed


  • BlockingQueue amazingly simplifies implementation of Producer-Consumer design pattern by providing outofbox support of blocking on put() and take().
  • No need of manual empty or full check, Blocking Queue handle it internally.
  • Only put and take operation required
  • Output is like one N produce and then consume like FIFO ordedr
  • Producer.java
    • public class Producer implements Runnable { private static BlockingQueue QUEUE; public Producer(BlockingQueue QUEUE_V) { QUEUE = QUEUE_V; } public void run() { try { int i = 1; while (true) { QUEUE.put(i); System.out.println(i + " Produced"); i++; } } catch (Exception e) { e.printStackTrace(); } } }

  • Consumer.java

    • public class Consumer implements Runnable { private static BlockingQueue QUEUE; public Consumer(BlockingQueue QUEUE_V) { QUEUE = QUEUE_V; } public void run() { consumer(); } private static void consumer() { int item; try { Thread.sleep(1000); while (true) { item = QUEUE.take(); System.out.println(item + " Consumed"); } } catch (Exception e) { e.printStackTrace(); } } }

  • App.java

    • private static BlockingQueue QUEUE = new ArrayBlockingQueue(10); public static void main(String[] args) { Thread producer = new Thread(new Producer(QUEUE)); Thread consumer = new Thread(new Consumer(QUEUE)); producer.start(); consumer.start(); }

  • Output

    • 1 Produced 2 Produced 3 Produced 4 Produced 5 Produced 6 Produced 7 Produced 8 Produced 9 Produced 10 Produced 1 Consumed 11 Produced 2 Consumed 3 Consumed 4 Consumed 5 Consumed 12 Produced 6 Consumed 13 Produced 7 Consumed 14 Produced 8 Consumed 15 Produced 9 Consumed 16 Produced 10 Consumed 17 Produced 11 Consumed 18 Produced


    • If List is full then our PRODUCER thread waits until CONSUMER thread consume one item and make space in your queue and call notify() method to inform PRODUCER thread. Both wait() and notify() method are called on shared object which is List in our case.
    • Need synchronised block
    • Check for List size manually and wait for consumer and producer threads
    • Since it is synchronised,
      • Needs to wait till N production
      • Needs to wait till N Consumption
    • Producer.java
      • public class Producer implements Runnable { private static List LIST; private static int SIZE; public Producer(List LIST_V, int SIZE_V) { LIST = LIST_V; SIZE = SIZE_V; } public void run() { producer(); } private static void producer() { try { int i = 1; while (true) { synchronized (LIST) { if (LIST.size() == SIZE) { System.out.println("Producer Waiting for consumer to consume object"); LIST.wait(); } LIST.add(i); System.out.println(i + " Produced"); LIST.notify(); } i++; if (i > 100) { break; } } } catch (Exception e) { e.printStackTrace(); } } }
    • Consumer.java
      • public class Consumer implements Runnable { private static List LIST; public Consumer(List LIST_V) { LIST = LIST_V; } public void run() { consumer(); } private static void consumer() { int index = 0; try { Thread.sleep(2000); while (true) { synchronized (LIST) { if (LIST.size() == 0) { System.out.println("Consumer is waiting for producer to produce"); LIST.wait(); } System.out.println(LIST.get(index) + " Consumed"); LIST.remove(index); LIST.notify(); } } } catch (Exception e) { e.printStackTrace(); } } }
    • App.java
      • public class App { private static List LIST = new ArrayList(); private static int SIZE = 10; public static void main(String[] args) { Thread producer = new Thread(new Producer(LIST, SIZE)); Thread consumer = new Thread(new Consumer(LIST)); producer.start(); consumer.start(); } }
    • Output
      • 1 Produced 2 Produced 3 Produced 4 Produced 5 Produced 6 Produced 7 Produced 8 Produced 9 Produced 10 Produced Producer Waiting for consumer to consume object 1 Consumed 2 Consumed 3 Consumed 4 Consumed 5 Consumed 6 Consumed 7 Consumed 8 Consumed 9 Consumed 10 Consumed Consumer is waiting for producer to produce 11 Produced 12 Produced 13 Produced

    Wednesday, 20 September 2017

    A matrix will be in M x N format.So what we need to do is, get value of indexes from 0,0 to M,N. Itreate the two dimensional array in diagonally as follow
    50 36 22 31 88 87 27 73 95
    After diagonal traverse the output will be.
    50 31 36 27 88 22 73 87 95
    Consider the above output
    50 31 36 27 88 22
    • These elements start from left to right top
    • Need to iterate for 0 to M-1 using for loop and display corresponding elements diagonally using a while loop.
    • To find next element use for formula: M-1,N+1 in while loop
    73 87 95
    • These elements start from bottom to right top
    • Need to Iterate form 1 to N-1 in for loop and display corresponding elements diagonally using a while loop.
    • So to find next element use for formula, M-1,N+1 in while loop

          TraveseMatrixDiagonally.java  
    public class TraveseMatrixDiagonally { private static final int M = 4; private static final int N = 4; public static void main(String[] args) { TraveseMatrixDiagonally app = new TraveseMatrixDiagonally(); int[][] matrix = app.createMatrix(); app.printMatrix(matrix); app.traverseDiagonally(matrix); } private void traverseDiagonally(int[][] matrix) { for (int i = 0; i <= M - 1; i++) { int X = i; // temp M int Y = 0; // temp N while (X >= 0 && Y <= N - 1) { System.out.print(matrix[X][Y] + " "); X = X - 1; Y = Y + 1; } System.out.println(" "); } for (int i = 1; i <= N - 1; i++) { int X = M - 1; int Y = i; while (X >= 0 && Y <= N - 1) { System.out.print(matrix[X][Y] + " "); X = X - 1; Y = Y + 1; } System.out.println(" "); } } private int[][] createMatrix() { int matrix[][] = new int[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { matrix[i][j] = (int) ((Math.random() * (99 + 1 - 10)) + 10); } } return matrix; } private void printMatrix(int[][] matrix) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { System.out.print(matrix[i][j]); System.out.print(" "); } System.out.println(" "); } } } /* ****** SAMPLE INPUT ******** 61 44 88 74 44 32 86 56 92 ******* INPUT ******** ****** SAMPLE OUTPUT ******** 61 74 44 86 44 88 56 32 92 ******* OUTPUT ******** */
    Reference Link https://www.youtube.com/watch?v=T8ErAYobcbc

    Tuesday, 19 September 2017

    A matrix will be in M x N format.So what we need to do is, get value of indexes from 0,0 to m,n. Itreate the two dimensional array in spiral mode as follow
    • we need to traverse matrix and remove the row/column which already traversed.
    • We are not going to delete the elements instead we will limit it by defining boundaries. 
    • Boundaries can be t, b, l, r we need to specify the direction variable dir. It decides the direction of traverse as below.
    • dir=0; ->right, dir=1 -> down, dir=2 -> left, dir=3 ->up

          TraverseMatrixSpiral.java  
    package com.sk.iwq.matrix; public class TraverseMatrixSpiral { private static final int M = 3; private static final int N = 3; public static void main(String[] args) { TraverseMatrixSpiral app = new TraverseMatrixSpiral(); int matrix[][] = app.createMatrix(); app.printMatrix(matrix); System.out.println(app.traverseSpriral(matrix).toString()); } private StringBuilder traverseSpriral(int[][] matrix) { StringBuilder sb = new StringBuilder(); int dir = 0; int t = 0; int b = M - 1; int l = 0; int r = N - 1; while (t <= b && l <= r) { if (dir == 0) { for (int i = l; i <= r; i++) { sb.append(matrix[t][i] + ", "); } t++; } if (dir == 1) { for (int i = t; i <= b; i++) { sb.append(matrix[i][r] + ", "); } r--; } if (dir == 2) { for (int i = r; i >= l; i--) { sb.append(matrix[b][i] + ", "); } b--; } if (dir == 3) { for (int i = b; i <= t; i++) { sb.append(matrix[i][l] + ", "); } l++; } dir = (dir + 1) % 4; } return sb; } private int[][] createMatrix() { int matrix[][] = new int[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { matrix[i][j] = (int) (Math.random() * 100 + 1); } } return matrix; } private void printMatrix(int[][] matrix) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { System.out.print(matrix[i][j]); System.out.print(" "); } System.out.println(" "); } } } /* ****** SAMPLE INPUT ******** 50 36 22 31 88 87 27 73 95 ******* INPUT ******** ****** SAMPLE OUTPUT ******** 50, 36, 22, 87, 95, 73, 27, 31, 88 ******* OUTPUT ******** */

    Monday, 18 September 2017

    Traverse the matrix in Java
    • A matrix will be in M x N format.
    • So what we need to do is, get value of indexes from 0,0 to m,n. 
    •  Itreate the two dimensional array as follow
    take 0(i) and traverse j till j < N
    take 1(i) and traverse j till j < N
               .
               .
    till M(i) and traverse j till j < N

          PrimeNumberCheck.java  
    public class TraverseMatrix { private static final int M = 3; private static final int N = 3; public static void main(String[] args) { TraverseMatrix app = new TraverseMatrix(); int matrix[][] = app.createMatrix(); app.printMatrix(matrix); app.normalTraverse(matrix); } private void normalTraverse(int[][] matrix) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { System.out.print(matrix[i][j]); System.out.print(", "); } } } private int[][] createMatrix() { int matrix[][] = new int[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { matrix[i][j] = (int) (Math.random() * 100 + 1); } } return matrix; } private void printMatrix(int[][] matrix) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { System.out.print(matrix[i][j]); System.out.print(" "); } System.out.println(" "); } } }

    To check the given number is prime or not.
    Prime Numbers:
    • A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
    •  It means the remainder of divison of N with numbers from 2 to N/2 should be grater than zero.
    Lets take 6  6%2=0, 6%3=0...from 2 to 3(2 to 6/2)
    here remainder is zero. So 6 is not prime number.
    Lets take 5 now
    5%2=1
    here remainder is greater than zero. So 5 is prime number.

          PrimeNumberCheck.java  
    public class PrimeNumberCheck { public static void main(String[] args) { PrimeNumberCheck app = new PrimeNumberCheck(); System.out.println("Eneter number:"); Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); System.out.println(app.isPrime(number)); } private boolean isPrime(int number) { boolean isPrime = true; for (int i = 2; i <= number / 2; i++) { if (number % i == 0) { return false; } } return isPrime; } } /* ****** INPUT ******** 5 ******* INPUT ******** ****** OUTPUT ******** true ******* OUTPUT ******** */

    Friday, 15 September 2017


    Order of Execution
    1. Parent Static Block 
    2. Child Static Block 
    3. Parent Normal Block 
    4. Parent Constructor 
    5. Child Normal Block 
    6. Child Constructor
    7. Child method invoked

    Animal.java 
    public class Animal { static { System.out.println("Animal Static Block "); } public Animal() { System.out.println("Animal Consuctor"); } { System.out.println("Animal Normal Block"); } public void aboutMe() { System.out.println("I am a Animal"); } }
    Cow.java
    public class Cow extends Animal { static { System.out.println("Cow Static Block "); } public Cow() { System.out.println("Cow Consuctor"); } { System.out.println("Cow Normal Block"); } public void aboutMe() { System.out.println("I am a Cow"); } }
    App.java
    public class App { public static void main(String[] args) { Cow cow = new Cow(); cow.aboutMe(); } }

    Tuesday, 12 September 2017


    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    Example:
    Given nums = [ 3, 4, 5, 2, 10, 8, 9 ]
    target = 19
    Because nums[4] + nums[6] = 10 + 9 = 19, return [4, 6]
    Approach:
    step1. take 3 and then add 3 with all other elements
    step2. take 4 and then add 4 with all other elements.Continue same till 9

     
          TwoSum.java  
    public class TwoSum { public static void main(String[] args) { int[] arr = { 3, 4, 5, 2, 10, 8, 9 }; int target = 19; TwoSum app = new TwoSum(); int[] rslt = app.twosum(arr, target); System.out.print(rslt[0] + ", " + rslt[1]); } private int[] twosum(int[] arr, int target) { int[] rslt = new int[2]; // take 3 and then add 3 with all other // take 4 and then add 4 with all other elemnts.Continue same till 9 for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (j != i) { // don't add the same indexes int sum = arr[i] + arr[j]; if (sum == target) { rslt[0] = i; rslt[1] = j; break; } } } } return rslt; } } /* ****** INPUT ******** { 3, 4, 5, 2, 10, 8, 9 } 19 ******* INPUT ******** ****** OUTPUT ******** 4, 6 ******* OUTPUT ******** */

    Friday, 8 September 2017


    All the uppercase letters should be converted to lowercase and all the lowercase letters should be converted to uppercase

     
          StringCaseSwith.java  
    import java.util.Scanner; /** * all the uppercase letters should be converted to lowercase and all the * lowercase letters should be converted to uppercase */ public class StringCaseSwith { public static void main(String[] args) { String c = ""; String rslt = ""; Scanner scanner = new Scanner(System.in); String str = scanner.next(); for (int i = 0; i < str.length(); i++) { c += str.charAt(i); if (c.equals(c.toUpperCase())) { rslt += c.toLowerCase(); } if (c.equals(c.toLowerCase())) { rslt += c.toUpperCase(); } c = ""; } System.out.println(rslt); } } /* ****** INPUT ******** Rob ******* INPUT ******** ****** OUTPUT ******** rOB ******* OUTPUT ******** */

    Thursday, 7 September 2017


    • Need to find missing number between 1 to N with low time complexity O(n).
    • Step1: Get sum of natural numbers from 1 to N as N x(N+1)/2
    • Step2: Get sum of array elements
    • Step3: Missing number = natural numbers sum - array sum
          FindMissingNumber.java
    public class FindMissingNumber { private static final int END_NUMBER = 10; private int getMissingNumber(int[] arr) { int missingNum = 0; int arrSum = 0; for (int i = 0; i < arr.length; i++) { arrSum += arr[i]; } int naturalSum = END_NUMBER * (END_NUMBER + 1) / 2; missingNum = naturalSum - arrSum; return missingNum; } public static void main(String[] args) { int[] arr = { 1, 2, 3, 0, 5, 6, 7, 8, 9, 10}; FindMissingNumber app = new FindMissingNumber(); int missingNum = app.getMissingNumber(arr); System.out.println("Missing Number = " + missingNum); } } ****** OUTPUT ******** Missing Number = 4 ******* OUTPUT ********

    Search This Blog

    Contact us

    Name

    Email *

    Message *