Saturday, May 15, 2021

Set of Spring Questions

 Useful Questions and Answers on click of this link

1. What is Hystrix server

2. Spring boot advantages

3. How to achieve distributed tx in micro service.

4. Without Spring boot, how will you create micro service in Java?

5. How to write Integration tests in Spring boot?

6. Difference between ribbon and feign client

7. Spring bean life cycles

8. Ways to set the properties to a spring bean before and after bean initialization

9. Different types of scopes in spring and difference between them.

10. @Component and @Bean differences.

11. Is Spring beans thread safe?

12. Circuit Breaker Pattern 

13. Can we customize spring boot sarters

24. In SAGA pattern what will happen to tx if microservice is down or failure

Sunday, May 2, 2021

Array Based questions asked in Interview

 Important Practice questions on click of this link


Programming Interview questions

One more

1. Find 2nd largest number in an given array.

   Constraint : 1. can only access each number by 1 times only.
                       2. Don't use any collection/Object. use only primitive type like int.
                       3. Complexity : O(n)
Solution: 

Below is the complete algorithm for doing this:  

1) Initialize two variables first and second to INT_MIN as
   first = second = INT_MIN
2) Start traversing the array,
   a) If the current element in array say arr[i] is greater
      than first. Then update first and second as,
      second = first
      first = arr[i]
   b) If the current element is in between first and second,
      then update second to store the value of current variable as
      second = arr[i]
3) Return the value stored in second.
// JAVA Code for Find Second largest
// element in an array
class GFG {
 
    /* Function to print the second largest
    elements */
    public static void print2largest(int arr[],
                                     int arr_size)
    {
        int i, first, second;
 
        /* There should be atleast two elements */
        if (arr_size < 2) {
            System.out.print(" Invalid Input ");
            return;
        }
 
        first = second = Integer.MIN_VALUE;
        for (i = 0; i < arr_size; i++) {
            /* If current element is smaller than
            first then update both first and second */
            if (arr[i] > first) {
                second = first;
                first = arr[i];
            }
 
            /* If arr[i] is in between first and
               second then update second  */
            else if (arr[i] > second && arr[i] != first)
                second = arr[i];
        }
 
        if (second == Integer.MIN_VALUE)
            System.out.print("There is no second largest"
                             + " element\n");
        else
            System.out.print("The second largest element"
                             + " is " + second);
    }
 
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = { 12, 35, 1, 10, 34, 1 };
        int n = arr.length;
        print2largest(arr, n);
    }
}
 2.) Longest substring with unique char (Without repeating) i/p : abcabdefgb ; o/p : defg
Answer: We start traversing the string from left to right and maintain track of:
  1. the current substring with non-repeating characters with the help of a start and end index
  2. the longest non-repeating substring output
  3. a lookup table of already visited characters
String getUniqueCharacterSubstring(String input) {
    Map<Character, Integer> visited = new HashMap<>();
    String output = "";
    for (int start = 0, end = 0; end < input.length(); end++) {
        char currChar = input.charAt(end);
        if (visited.containsKey(currChar)) {
            start = Math.max(visited.get(currChar)+1, start);
        }
        if (output.length() < end - start + 1) {
            output = input.substring(start, end + 1);
        }
        visited.put(currChar, end);
    }
    return output;
}

For every new character, we look for it in the already visited characters. If the character has already been visited and is part of the current substring with non-repeating characters, we update the start index. Otherwise, we'll continue traversing the string.

Since we are traversing the string only once, the time complexity will be linear, or O(n).

This approach is also known as the sliding window pattern.

3.)Next immediate bigger number, using combination of digit. ex : i/p :1234 ;o/p :1243
Solution:

Following are few observations about the next greater number. 
1) If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321. 
2) If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234. 
3) For other cases, we need to process the number from rightmost side (why? because we need to find the smallest of all greater numbers)

You can now try developing an algorithm yourself. 
Following is the algorithm for finding the next greater number. 
I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.

II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.



III) Swap the above found two digits, we get 536974 in above example.

IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.

// Java program to find next greater
// number with same set of digits.
import java.util.Arrays;
 
public class nextGreater
{
    // Utility function to swap two digit
    static void swap(char ar[], int i, int j)
    {
        char temp = ar[i];
        ar[i] = ar[j];
        ar[j] = temp;
    }
 
    // Given a number as a char array number[],
    // this function finds the next greater number.
    // It modifies the same array to store the result
    static void findNext(char ar[], int n)
    {
        int i;
         
        // I) Start from the right most digit
        // and find the first digit that is smaller
        // than the digit next to it.
        for (i = n - 1; i > 0; i--)
        {
            if (ar[i] > ar[i - 1]) {
                break;
            }
        }
         
        // If no such digit is found, then all
        // digits are in descending order means
        // there cannot be a greater number with
        // same set of digits
        if (i == 0)
        {
            System.out.println("Not possible");
        }
        else
        {
            int x = ar[i - 1], min = i;
             
            // II) Find the smallest digit on right
            // side of (i-1)'th digit that is greater
            // than number[i-1]
            for (int j = i + 1; j < n; j++)
            {
                if (ar[j] > x && ar[j] < ar[min])
                {
                    min = j;
                }
            }
 
            // III) Swap the above found smallest
            // digit with number[i-1]
            swap(ar, i - 1, min);
 
            // IV) Sort the digits after (i-1)
            // in ascending order
            Arrays.sort(ar, i, n);
            System.out.print("Next number with same" +
                                    " set of digits is ");
            for (i = 0; i < n; i++)
                System.out.print(ar[i]);
        }
    }
 
    public static void main(String[] args)
    {
        char digits[] = { '5','3','4','9','7','6' };
        int n = digits.length;
        findNext(digits, n);
    }
}

5.) Given a String "Kunwar jee Pathak". Print output as "Kunwr j Pthk" . All duplicates to be removed.

Solution

1) By using indexOf() method

Thisway of removing duplicate characters from a string is by using the indexOf() method. In this method, we will work on the index position of the character. In order to remove the duplicate character from the string, we will use the following steps:

  • In the main() method, we will create a string from which we have to remove duplicate characters.
  • We will call the removeDuplicates() method and passed the string from which we need to remove duplicate characters.
  • In the removeDuplicates() method, we will create a new empty string and calculate the original string's length.
  • We will traverse the string using the loop and check for repeating characters using the indexOf() method.
  • The indexOf() method returns -1 when the element is not present. So, when the string doesn't contain that character, we will add it to the empty string.

RemoveDuplicatesExample4.java

  1. // import classes and packages   
  2. import java.util.*;   
  3. //Create RemoveDuplicatesExample4 class to remove duplicates from the string   
  4. class RemoveDuplicatesExample4 {   
  5.         
  6.     // Create removeDuplicates() method to remove duplicates using indexOf() method  
  7.     public static void removeDuplicates(String str)   
  8.     {   
  9.         //Create an empty string   
  10.         String newstr = new String();   
  11.           
  12.         //calculate length of the original string  
  13.         int length = str.length();   
  14.             
  15.         // Traverse the string and check for the repeated characters   
  16.         for (int i = 0; i < length; i++)    
  17.         {   
  18.             // store the character available at ith index in the string  
  19.             char charAtPosition = str.charAt(i);   
  20.             // check the index of the charAtPosition. If the indexOf() method returns true add it to the resuting string  
  21.             if (newstr.indexOf(charAtPosition) < 0)   
  22.             {   
  23.                 newstr += charAtPosition;   
  24.             }   
  25.         }   
  26.         //Print string after removing duplicate characters   
  27.         System.out.println(newstr);  
  28.     }   
  29.     
  30.     // main() method start  
  31.     public static void main(String[] args)   
  32.     {   
  33.         // Create a string variable with default value   
  34.         String str = "JavaTpoint is the best learning website";   
  35.         //call removeDuplicates() method for removing duplicate characters    
  36.         removeDuplicates(str);   
  37.     }   
  38. }  

By using for loop

It is the simplest way of removing duplicates characters from a string. We should have to use the following steps for removing duplicates.

  1. In the first step, we have to convert the string into a character array.
  2. Calculate the size of the array.
  3. Call removeDuplicates() method by passing the character array and the length.
  4. Traverse all the characters present in the character array.
  5. Check whether the str[i] is present before or not. If it is not present before, add it to the result.

Let's implement the above theory's code to understand how this method works to remove duplicates from a string.

RemoveDuplicatesExample1.java

  1. //Import packages   
  2. import java.util.*;   
  3.   
  4. //Creating RemoveDuplicatesExample1 class  
  5. class RemoveDuplicatesExample1    
  6. {   
  7.     //Creating removeDuplicates() method to remove duplicates from array  
  8.     static void removeDuplicate(char str[], int length)   
  9.     {   
  10.         //Creating index variable to use it as index in the modified string   
  11.         int index = 0;   
  12.     
  13.         // Traversing character array  
  14.         for (int i = 0; i < length; i++)   
  15.         {   
  16.               
  17.             // Check whether str[i] is present before or not   
  18.             int j;   
  19.             for (j = 0; j < i; j++)    
  20.             {   
  21.                 if (str[i] == str[j])   
  22.                 {   
  23.                     break;   
  24.                 }   
  25.             }   
  26.     
  27.             // If the character is not present before, add it to resulting string   
  28.             if (j == i)    
  29.             {   
  30.                 str[index++] = str[i];   
  31.             }   
  32.         }   
  33.         System.out.println(String.valueOf(Arrays.copyOf(str, index)));   
  34.     }   
  35.     
  36.     // main() method starts  
  37.     public static void main(String[] args)   
  38.     {   
  39.         String info = "javaTpoint is the best learning website";  
  40.         //Converting string to character array  
  41.         char str[] = info.toCharArray();  
  42.         //Calculating length of the character array  
  43.         int len = str.length;   
  44.         //Calling removeDuplicates() method to remove duplicate characters  
  45.         removeDuplicate(str, len);   
  46.     }   
  47. }  
6.) Find Missing Number
input[1,2,7,6,4,3]
output[5]
Use Sum formula
-> Get the sum of number
     total= n*(n+1)/2;
-> Subtract all the numbers from the sum and you will find missing number
     int main()
{   
         int a[]= {1,2,4,5,6}
         int miss= getMissingNo(a,5)
}
     int getMissingNo(int a[], int n)
     {
       int i, total;
       total = (n+1)*(n+2)/2;
       for(int i=0; i<n; i++){
            total = total - a[i];
            return total;
       }
7.) Insert Operation
//In an unsorted array, the insert operation is faster as compared to sorted array because we don't have //to care about the position at which the element to be placed.
  int main()
  {
     int arr[20] = {12,16,20,40,50,70};
     int capacity = sizeof(arr)/sizeof(arr[0]);
     int n=6;
     int i, key=26;
          n = insertSorted(arr, n .key, capacity);
  }
 // Inserts a key in arr[] of given capacity, n is current size of arr[]. This function returns n+1 if //insertion is successful else n.
int insertSorted( int arr[], int n, int key, int capacity)
{
   if( n>= capacity)
   return n;
   int i;
   for ( i=n-1; (arr[i] > key && i>0); i--)
   {
     arr[i+1] = arr[i];
   }
   arr[i+1]=key;
   return(n+1);
  //after for loop
}
8.) Search, Insert and Delete in a sorted array
1.) Search using binary:
      int main()
      {
         int arr[]={5,6,7,8,9,10};
         int n, key;
         n=sizeof(arr)/sizeof(arr[0]);
         key=10;
         binarySearch(arr, 0, n, key);
      }
      int binarySearch( int arr[], int low, int high, int key)
      {
         if( high < low)
            return-1;
            int mid = (low+high)/2;
            if ( key == arr[mid])
                return mid;
            if (key > arr[mid]) 
                return binarySearch( arr, (mid+1), high, key);
            return binarySearch(arr, low, (mid-1), key);
       }

      
9.) Delete Operation
//The element to be deleted is searched using binary and then delete operation is performed by //shifting the elements
 int main()
 {
   int i;
   int arr[] = {10,20,30,40,50};
   int n = sizeof(arr) / sizeof(arr[0]);
   int key =30;
   n = deleteElement(arr, n , key);
}
   int deleteElement ( int arr[], int n, int key)
   {
    //find position of element to be deleted
      int pos = binarySearch(arr, 0, n-1, key);
      if (pos ==-1)
      { //element not found}
      //deleting
      int i;
      for( i=pos; i<n; i++){
         arr[i] = arr[i+1];
      }
        return n-1;
    }















Top DataStructures Problem from Medium-2

  Array: Find a pair with the given sum in an array Maximum Sum Subarray Problem (Kadane’s Algorithm) Longest Increasing Subsequence Problem...