Monday, August 26, 2019

How do you sort the keys in HashMap?

Problem statement:
Write the java code to sort the keys in HashMap.

  1. import java.util.HashMap;
  2. import java.util.Set;
  3. import java.util.TreeSet;
  4. public class Test {
  5. public static void main(String[] args) {
  6. HashMap<String, String> m = new HashMap<String, String>();
  7. m.put("key45", "aa");
  8. m.put("key12", "zz");
  9. m.put("key39", "cc");
  10. m.put("key27", "bb");
  11. Set<String> s = m.keySet();
  12. s = new TreeSet<String>(s);
  13. System.out.println(s);
  14. }
  15. }
Output:
[key12, key27, key39, key45]

How do you sort the values in HashMap?

Problem statement:
Write the java code to sort the values in HashMap.
  1. import java.util.Collection;
  2. import java.util.HashMap;
  3. import java.util.TreeSet;
  4. public class Test {
  5. public static void main(String[] args) {
  6. HashMap<String, String> m = new HashMap<String, String>();
  7. m.put("key45", "aa");
  8. m.put("key12", "zz");
  9. m.put("key39", "cc");
  10. m.put("key27", "bb");
  11. Collection<String> c = m.values();
  12. c = new TreeSet<String>(c);
  13. System.out.println(c);
  14. }
  15. }
Output:
[aa, bb, cc, zz]

Which of the following option will sort the keys in HashMap ?

Problem statement:
Given java code as follows, can you find out the correct option to sort the keys in HashMap?
  1. import java.util.HashMap;
  2. import java.util.Set;
  3. import java.util.TreeSet;
  4. public class Test {
  5. public static void main(String[] args) {
  6. HashMap<String, String> m = new HashMap<String, String>();
  7. m.put("key45", "aa");
  8. m.put("key12", "bb");
  9. m.put("key39", "cc");
  10. Set<String> s = m.keySet();
  11.   // code goes here
  12. s = new TreeSet(s);
  13.  }
  14. }
  • Arrays.sort(s);
  • s = new TreeSet(s);
  • Collections.sort(s);
  • s = new SortedSet(s);
Correct option: 
s = new TreeSet(s);
Explanation:
Arrays.sort(s) // sorts for static array 
Collection.sort(s) // sort the List type of object not Set type
s =new SortedSet(s); // SortedSet is an interface

Saturday, August 24, 2019

Write an algorithm to find N’th smallest element in an Unsorted Array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth smallest element in the array.

  1. public class NthSmallestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4.   int thirdSmallest = 3;
  5. int min= nthSmallestElement(a, thirdSmallest );
  6. System.out.println(min);
  7. }
  8. public static int nthSmallestElement(int a[], int n) {
  9. // Sort the given array
  10. Arrays.sort(a);
  11. // Return n'th element in the sorted array
  12. return a[n - 1];
  13. }
  14. }
Output:
3

Write an algorithm to find N’th largest element in an Unsorted Array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth largest element in the array.
  1. public class NthLargestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4.                 int thirdLargest = 3;
  5. int max = nthLargestElement(a, thirdLargest);
  6. System.out.println(max);
  7. }
  8. public static int nthLargestElement(int a[], int n) {
  9. // Sort the given array
  10. Arrays.sort(a);
  11. // Return n'th element in the sorted array
  12. return a[a.length - n];
  13. }
  14. }
Output:
4

Write an algorithm to find out the second smallest element in an array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the second smallest element in the array.

  1. public class SecondMinElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4. int firstMin = Integer.MAX_VALUE;
  5. int secondMin = Integer.MAX_VALUE;
  6. for (int i = 0; i < a.length; i++) {
  7. if (a[i] < firstMin) {
  8. secondMin = firstMin;
  9. firstMin = a[i];
  10. } else if (a[i] < secondMin) {
  11. secondMin = a[i];
  12. }
  13. }
  14. System.out.println("Second min element: " + secondMin);
  15. }
  16. }
Output:
Second min element: 1

Write an algorithm to find out the second largest element in an array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the second largest element in the array.
  1. public class SecondMaxElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4. int firstMax = Integer.MIN_VALUE, // large -ve value
  5.   int secondMax = Integer.MIN_VALUE; // large -ve value
  6. for (int i = 0; i < a.length; i++) {
  7. if (a[i] > firstMax) {
  8. secondMax = firstMax;
  9. firstMax = a[i]; // a[0] becomes first max
  10. } else if (a[i] > secondMax) {
  11. secondMax = a[i];
  12. }
  13. }
  14. System.out.println(secondMax);
  15. }
  16. }
Output:
10

What is the output of the given java code?

Problem statement:
Given java code, what will be the output of it?
  1. interface Car {
  2. public void startEngine();
  3. }
  4. class MySuzuki implements Car {
  5. public void startEngine() {
  6. System.out.println("MySuzuki");
  7. }
  8. }
  9. class MyFerrari implements Car {
  10. public void startEngine() {
  11. System.out.println("MyFerrari");
  12. }
  13. }
  14. public class OOPSExample {
  15. public static void main(String[] args) {
  16. MyFerrari obj = new MySuzuki();
  17. obj.startEngine();
  18. }
  19. }
Output:
Compile time error at line 16, due to Type mismatch: cannot convert from MySuzuki to MyFerrari

What is the output of the code?

Problem statement:
Given java code, what will be the output of it?
  1. interface Car {
  2. public void startEngine();
  3. }
  4. class MySuzuki implements Car {
  5. public void startEngine() {
  6. System.out.println("MySuzuki");
  7. }
  8. }
  9. class MyFerrari implements Car {
  10. public void startEngine() {
  11. System.out.println("MyFerrari");
  12. }
  13. }
  14. public class OOPSExample {
  15. public static void main(String[] args) {
  16. Car obj = new MySuzuki();
  17. obj.startEngine();
  18. }
  19. }
Output:
MySuzuki

Can you write an algorithm to check palindrome?

Problem statement:
Given a string. Can you check whether it is a palindrome or not?
  1. public class Palindrome {
  2. public static void main(String[] args) {
  3. String s = "abcba";
  4. char c[] = s.toCharArray();
  5. int p = c.length - 1;
  6. for (int i = 0; i < c.length / 2; i++) {
  7. if (c[i] == c[p]) {
  8. p--;
  9. } else {
  10. System.out.println("Not palindrome");
  11. return;
  12. }
  13. }
  14. System.out.println("Palindrome");
  15. }
  16. }
Output:
Palindrome
Time complexity: O(n/2)

How will you find smallest element in an array?

Problem statement:
Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the given array?
  1. public class LargestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 5, 0, -10 };
  4. int max = Integer.MIN_VALUE;  //-2147483648
  5. for (int i = 0; i < a.length; i++) {
  6. if (a[i] > max) {
  7. max = a[i];
  8. }
  9. }
  10. System.out.println("max: " + max);
  11. }
  12. }
Output:
max: 5

How will you find smallest element in an array?

Problem statement:
Given an array of positive or negative integer. How will you write an algorithm to find out the smallest element in the given array?
  1. public class SmallestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 5, 0, -10, -40 };
  4. int min = Integer.MAX_VALUE; // 2147483647
  5. for (int i = 0; i < a.length; i++) {
  6. if (a[i] < min) {
  7. min = a[i];
  8. }
  9. }
  10. System.out.println("min: " + min);
  11. }
  12. }
Output:
min: -40

Wednesday, August 21, 2019

What do you mean by Association, Aggregation and Composition in Java?

What is the difference between Hashtable and ConcurrentHashMap

What is the difference between Hashtable & HashMap?

What are different ways of creating a thread in java?

How do you stop a running thread?

What is heap memory and stack memory in java?

Can we overload constructor in java?

Problem statement:
You are given a code for constructor overloading. What do you think, can we overload the constructor in java?

Ans: Yes.
  1. class A {
  2. A() {
  3. System.out.println("default");
  4. }
  5. A(int id) {
  6. System.out.println("id");
  7. }
  8. A(int id, String name) {
  9. System.out.println("id & name");
  10. }
  11. A(String name, Double salary) {
  12. System.out.println("name & salary");
  13. }
  14. }
  15. public class Sample {
  16. public static void main(String[] args) {
  17. A a = new A();
  18. }
  19. }
Output:
default

Can we override constructor in java?

Problem statement:
You are given a code for constructor overriding. What do you think, can we override the constructor in java?

Ans: No.
  1. class A {
  2. A() {
  3. System.out.println("A of A");
  4. }
  5. }
  6. class B extends A {
  7. A() {
  8. System.out.println("A of B");
  9. }
  10. }
  11. public class Sample {
  12. public static void main(String[] args) {
  13. B b = new B();
  14. }
  15. }
Output:
Return type of method is missing, meaning compiler is treating A() as a method not as a constructor and also compiler is expecting return type for the method A(), because in code there is no return type.

Saturday, August 17, 2019

what will happen when you run the following code?

Problem statement:
Given the java code. what will be the output?
  1. public class Test {
  2. static void test() throws RuntimeException {
  3. try {
  4. System.out.println("test");
  5. throw new RuntimeException();
  6. } catch (Exception ex) {
  7. System.out.println("exception");
  8. }
  9. }
  10. public static void main(String[] args) {
  11. try {
  12. test();
  13. throw new RuntimeException();
  14. } catch (RuntimeException ex) {
  15. System.out.println("runtime");
  16. System.out.println("end");
  17. }
  18. }
  19. }
Output:
test
exception
runtime
end

Friday, August 16, 2019

What is the output of the following code?

Problem statement:
Given the code of java. Find out the output.
  1. public class Test {
  2. static void test() throws RuntimeException {
  3. try {
  4. System.out.println("test");
  5. throw new RuntimeException();
  6. } catch (Exception ex) {
  7. System.out.println("exception");
  8. }
  9. }
  10. public static void main(String[] args) {
  11. try {
  12. test();
  13. } catch (RuntimeException ex) {
  14. System.out.println("runtime");
  15. }
  16.     System.out.println("end");
  17. }
  18. }
Output:
test
exception
end

Sunday, August 11, 2019

What is the output of the following code?

Problem statement: 
Given the code of java. Can you tell me the output of this?
  1. interface Annonymous {
  2.     public int getValue();
  3. }
  4. public class Sample1 {
  5.     int data = 15;
  6.     public static void main(String[] args) {
  7.         Annonymous a = new Annonymous() {
  8.             int data = 5;
  9.             public int getValue() {
  10.                 return data;
  11.             }
  12.             public int getData() {
  13.                 return data;
  14.             }
  15.         };
  16.         Sample1 s = new Sample1();
  17.         System.out.println(a.getValue() + a.getData() + s.data);
  18.     }
  19. }
Output:
compilation error at line number 17 due to a.getData(). Here getData() is not a method of Annonymous interface.

What is the output of the following code?

Problem statement: Given the code of java. Can you tell me the output of this?
  1. interface Annonymous {
  2.     public int getValue();
  3. }
  4. public class Sample1 {
  5.     int data = 15;
  6.     public static void main(String[] args) {
  7.         Annonymous a = new Annonymous() {
  8.             int data = 5;
  9.             public int getValue() {
  10.                 return data;
  11.             }
  12.             public int getData() {
  13.                 return data;
  14.             }
  15.         };
  16.         Sample1 s = new Sample1();
  17.         System.out.println(a.getValue() + s.data);
  18.     }
  19. }
Output:
20

Wednesday, July 31, 2019

How do you get the day from Date and Time?

Problem statement:
You are given a date. You just need to write the method, , which returns the day on that date.
For example, if you are given the date August 14th 2017 the method should return MONDAY as the day on that date.
  1. public static String findDay(int mm, int dd, int yy) 
  2. {
  3. java.time.LocalDate dt = java.time.LocalDate.of(yy, mm, dd);
  4. return dt.getDayOfWeek().name();
  5. }
Output: MONDAY

Thursday, July 11, 2019

How do you solve problem based on Counting Valleys?

Problem statement:
Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly n steps. For every step he took, he noted if it was an uphill, U, or a downhill, D step. Gary's hikes start and end at sea level and each step up or down represents a 1 unit change in altitude. We define the following terms:
  • A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
  • A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is s=[DDUUUUDD] he first enters a valley 2 units deep. Then he climbs out an up onto a mountain 2 units high. Finally, he returns to sea level and ends his hike.

Input Format:
The first line contains an integer n, the number of steps in Gary's hike. 
The second line contains a single string s, of n characters that describe his path.

Constraints:
2 <= n<=10^6

Output Format:
Print a single integer that denotes the number of valleys Gary walked through during his hike.

Sample Input:
8
UDDDUDUU

Sample Output:
1

Explanation:
If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as:

_/\      _
   \    /
    \/\/
He enters and leaves one valley.

Solution:

  1. // countingValleys function below.
  2.     static int countingValleys(int n, String s) {
  3.         char c[] = s.toCharArray();
  4.         int lvl = 0;    // level
  5.         int v = 0;      // valley
  6.         for(int i = 0; i <c.length; i++)
  7.         {
  8.             if(c[i] == 'U')
  9.             {
  10.                 lvl = lvl +1;
  11.             }
  12.             if(c[i] == 'D')
  13.             { 
  14.                 lvl = lvl -1;
  15.             }
  16.             if(lvl == 0 && c[i] == 'U')
  17.             {
  18.                 v = v +1;
  19.             }
  20.         }
  21.         return v;
  22.     }

Wednesday, July 10, 2019

How do you solve the problem of a sock merchant?

Problem statement:
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are n = 7 socks with colors ar = [1,2,1,2,1,3,2] . There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

Input Format:
The first line contains an integer n, the number of socks represented in ar

The second line contains n space-separated integers describing the colors ar[i] of the socks in the pile.

Constraints:
1 <= n <=100
1 <= ar[i] <= 100 where 0 <= i < n

Output Format:
Return the total number of matching pairs of socks that John can sell.

Sample Input:
9
10 20 20 10 10 30 50 10 20

Sample Output:
3
  1. // sockMerchant function below.
  2.     static int sockMerchant(int n, int[] ar) {        
  3.         int count = 0;
  4.         Arrays.sort(ar);
  5.         for(int i = 0; i < ar.length-1; i++)
  6.         {
  7.             if(ar[i] == ar[i+1])
  8.             {
  9.                 count = count+1; // count++;
  10.                 //i+=1;
  11.                 i = i+1;        
  12.             }
  13.         }        
  14.         return count;
  15.     }

Wednesday, June 26, 2019

LinkedList problem statement?

Problem statement:
Given a LinkedList as follows, first can you write an algorithm to check whether this LinkedList is 
creating loop or not?
second if yes then how?
1 -> 2 -> 3 -> 4 -> 5 -> 6 ->3

Write an algorithm for the following problem statements !!

Problem statement:
Given two array as follows. 
a1[] = {1, 2, 3, 4, 5}
a2[] = {1, 2, 3, 0, 5}

we need to find out the missing element in second array which is present in first array, but not in second array.

Can you write the algorithm for the following statement?

Problem statement:
Given an array of integer, you need to write an algorithm so that it prints the expected behaviour?

Sample Input:
a[] = {1, 0, 2, 0, 3, 0}

Sample Ouput:

a[] = {1, 2, 3, 0, 0, 0}

Saturday, June 22, 2019

Can you write the code for switch statements using enum in Java SE 8 ?

Problem statement:
Write a program for switch statements using enum in Java.
  1. enum APP {
  2.     Google, Yahoo, Apple, HP
  3. }
  4. public class SwitchStatement {
  5.     public static void main(String[] args) {
  6.         APP c = APP.Google;
  7.         switch (c) {
  8.             case Apple:
  9.                 System.out.println("You choose Apple.");
  10.                 break;
  11.             case Google:
  12.                 System.out.println("You choose Google.");
  13.                 break;
  14.             case Yahoo:
  15.                 System.out.println("You choose Yahoo.");
  16.                 break;
  17.             case HP:
  18.                 System.out.println("You choose HP.");
  19.                 break;
  20.             default:
  21.                 System.out.println("default");
  22.                 break;
  23.         }
  24.     }
  25. }
Output:
You choose Google.

what are the data types we cannot use in switch statement?

Problem statement:
what are the data types you cannot use as a parameter variable for switch statements in Java 8?

Following are the data types we cannot use as an input parameter variable for switch() statements.
  1. long
  2. float
  3. double
Error: Incompatible type found long, float and double.

public class SwitchStatement {
    public static void main(String[] args) {
        double d = 10.5d;
        switch (d) {
            case 10.5d:
                System.out.println("double");
                break;            
            default:
                System.out.println("default");
                break;
        }
    }
}
Error: Incompatible types. Found: 'double'

what are the data types we can use in switch statement?

Problem statement:
what are the data types you can use as a parameter variable for switch statements in Java 8?
Following are the data types we can use as an input parameter variable for switch() statements.
  1. byte
  2. short
  3. int
  4. char
Add-On:
  1. String 
  2. enum

Monday, May 20, 2019

Can you write an algorithm to print the following pattern?

Problem statement:
Given an input string from the console as follows

Sample I/O:

aaaaa, bbbb, cccc, d , f , g , i
Sample O/P:
a5, b4, c4,d1, f1, h1, g1, i1
  1. import java.util.Scanner;
  2. public class SwitchStatement {
  3.     public static void main(String[] args) {
  4.         Scanner sc = new Scanner(System.in);
  5.         System.out.println("Enter the pattern.");
  6.         String pattern = sc.nextLine();
  7.         System.out.println(pattern.charAt(0) + "" + pattern.length());
  8.     }
  9. }

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...