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

Leetcode: 463. Island Perimeter


You are given a map in the form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
 Example:
Input:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:


PROGRAM:


class Solution {
 
    public int islandPerimeter(int[][] grid) {
        int wallCount = 0;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(grid[i][j] == 1){
                    
                    if(j == 0) wallCount++;
                    else if(j > 0 && grid[i][j-1] == 0) wallCount++;
                    
                    if(i == 0) wallCount++;
                    else if(i > 0 && grid[i-1][j] == 0) wallCount++;
                    
                    if(j+1 >= grid[0].length) wallCount++;
                    else if(grid[i][j+1] == 0) wallCount++;
                    
                    if(i+1 >= grid.length) wallCount++;
                    else if(grid[i+1][j] == 0) wallCount++;
                }
            }
        }
        return wallCount;
    }
}


OUTPUT:

16

Enum.ordinal() Method in Java

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). For example, let's have weekdays in an enum starting from Monday, Tuesday till Sunday. So the ordinal of Monday will be 0, Tuesday will be 1, etc.,

Enum.ordinal() Method in Java


Let's see simple Java for the same.


enum Days{
// 0 1  2     3         4       5  6 
 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumOrdinal {
 public static void main(String[] args) {
  Days mon = Days.MONDAY;
  Days wed = Days.WEDNESDAY;
  Days tus = Days.TUESDAY;
  Days fri = Days.FRIDAY;
  Days sun = Days.SUNDAY;
  
  System.out.println("Monday ordinal    : "+mon.ordinal());
  System.out.println("Wednesday ordinal : "+wed.ordinal());
  System.out.println("Tuesday ordinal   : "+tus.ordinal());
  System.out.println("Friday ordinal    : "+fri.ordinal());
  System.out.println("Sunday ordinal    : "+sun.ordinal());
 }
}


OUTPUT:


Monday ordinal    : 0
Wednesday ordinal : 2
Tuesday ordinal   : 1
Friday ordinal    : 4
Sunday ordinal    : 6

Find the Occurrences Of Each Character In a String

Find the Occurrences Of Each Character In a String without using collection.
Here we are going to create simple array to store the character occurrence. If we look at ASCII value of each character including space then it starts from 32 to 126. So we will create array size of 94 which can hold all the character occurrences.

Find the Occurrences Of Each Character In a String


Let's see simple example in Java how to implement in a simple way.

public class CharacterOccurrance {

 public static void main(String[] args) {
  String str = "Java Discover~";

  CharacterOccurrance obj = new CharacterOccurrance();
  int[] occurrance = obj.findCharOccurrance(str);
  obj.printOccurrance(occurrance);
 }

 public int[] findCharOccurrance(String str) {
  int[] occurrance = new int[95];
  for (int i = 0; i < str.length(); i++) {
   int index = str.charAt(i);
   occurrance[index - 32]++;
  }
  return occurrance;
 }

 public void printOccurrance(int[] occurrance) {
  System.out.println("Character : Occurrance");
  for (int i = 0; i < occurrance.length; i++) {
   if (occurrance[i] > 0) {
    char ch = (char) (i + 32);
    System.out.println(ch + " \t  : " + occurrance[i]);
   }
  }
 }
}



OUTPUT:


Character : Occurrance
     : 1          <----- Space
D    : 1
J    : 1
a    : 2
c    : 1
e    : 1
i    : 1
o    : 1
r    : 1
s    : 1
v    : 2
~    : 1

Longest palindrome Sub-sequence from the given String using Dynamic Programming

Write a program to find the longest sub-sequence palindrome from the given string by using dynamic programming. For example

Input String : ABCDQRDC

Longest sub-sequence palindrome: 5
Longest palindrome Sub-sequence from the given String using Dynamic Programming

  •  So let's see how we will solve and find the longest subsequence palindrome using dynamic programming. 

  • Construct the solution matrix of size NxN where N is the length of given string. 
  • We will calculate the size of each character sequence palindrome size and will the memorised in the solution matrix which will referred for the next incremental sequence.
  • For example in above example all strings of 1 character will be palindrome size of 1. A, B, C, D, Q, R, D, C
  • On next cycle it will add another character and makes 2 character string like 
  • AB, BC, CD, DQ, QR, RD, DC and goes on like 
  • ABC, BCD, CDQ, DQR, QRD, RDC etc.,
  • Each sequences palindrome size will be stored in the solution array and finally returns the maximum size as output.
Now lets see simple Java code 


 public class LongestPalindromeSequence {

 public static void main(String[] args) {

  String str = "ABCDQRDC";

  LongestPalindromeSequence obj = new LongestPalindromeSequence();

  System.out.println("\nLength of Longest palindrome subsequence : " + obj.lps(str));

 }

 public int lps(String seq) {
  int n = seq.length();
  int j, k, i;
  int L[][] = new int[n][n];

  // Strings of 1 character will be palindrome size of 1 
  // starting with upper matrix and all single character falls diagonally and size will be 1
  for (j = 0; j < n; j++)
   L[j][j] = 1;

  for (i = 2; i <= n; i++) {
   for (j = 0; j < n - i + 1; j++) {

    k = j + i - 1;

    if (seq.charAt(j) == seq.charAt(k)) {
     L[j][k] = L[j + 1][k - 1] + 2;

    } else {
     L[j][k] = Math.max(L[j][k - 1], L[j + 1][k]);
    }
   }
  }

  /*System.out.println("Final solution Matrix :::: ");
  for (j = 0; j < n; j++) {
   System.out.print(seq.charAt(j) +" - ");
   for (k = 0; k < n; k++) {
    System.out.print(L[j][k] + "\t");
   }
   System.out.println();
  }*/
  return L[0][n - 1];
 }
}

OUTPUT:


Length of Longest palindrome subsequence : 5

Reverse words in a given String using recursion

Reverse words in a given String using recursion. We need to reverse words by words in a given line and not the character in a given string. We need to solve this by using backtracking and recursion logic.
Reverse words in a given String using recursion

Let's see simple Java code for getting the given of words in a reverse order by using recursion.


public class ReverseLineByWords {

 public static void main(String[] args) {
  
  String str = "Hello Java Discover";
  
  String finalStr = new ReverseLineByWords().reverseLine(str);
  
  System.out.println(finalStr);
  
 }
 
 public String reverseLine(String str){
  String word = "";
  int i = 0;
  for(;i<str.length();i++){
   if(str.charAt(i) == ' ') {
    word = word + " ";
    break;
   }else{
    word = word + str.charAt(i);
   }
  }

  if(i < str.length()) 
   return reverseLine(str.substring(i+1)) + word;
  
  return (word + " ");
 }
}


OUTPUT:


Discover Java Hello 


Rotate matrix by clockwise

Given a NxN matrix and need to rotate by clockwise as given below

Examples:
Rotate matrix by clockwise


Let's see simple java code to rotate given NxN matrix.


public class MatrixRotate {

 private int prev, curr;

 public static void main(String[] args) {

  int[][] matrix = new int[][] { { 1, 2, 3, 4 }, 
                   { 5, 6, 7, 8 }, 
            { 9, 10, 11, 12 }, 
            { 13, 14, 15, 16 } };
  

  MatrixRotate obj = new MatrixRotate();
  obj.rotateMatrix(matrix);

  for (int i = 0; i < matrix.length; i++) {
   System.out.println();
   for (int j = 0; j < matrix[0].length; j++) {
    System.out.print(matrix[i][j] + ", ");
   }
  }
 }

 public void rotateMatrix(int[][] matrix) {

  int r = matrix.length;
  int c = matrix[0].length;
  int row = 0, col = 0;

  for (int cnt = 0;cnt<(r*c);cnt++) {
   
   prev = matrix[row + 1][col];

   for (int i = col; i < c; i++) {
    swap(row, i, matrix); cnt++;   }
   row++;

   for (int i = row; i < r; i++) {
    swap(i, c - 1, matrix); cnt++;   }
   c--;

   if (row < r) {
    for (int i = c - 1; i >= col; i--) {
     swap(r - 1, i, matrix); cnt++;
    }
   }
   r--;

   if (col < c) {
    for (int i = r - 1; i >= row; i--) {
     swap(i, col, matrix); cnt++;
    }
   }
   col++;
  }
 }

 public void swap(int i, int j, int matrix[][]) {
  curr = matrix[i][j];
  matrix[i][j] = prev;
  prev = curr;
 }
}


OUTPUT:


 5,  1,  2,  3, 
 9, 10,  6,  4, 
13, 11,  7,  8, 
14, 15, 16, 12,