![]() |
Programming Interview Questions |
Q1. Write a program to check if two strings are ANAGRAM to each other or not?
So, two strings will be called ANAGRAM if the character count of both the strings is the same and the same characters are present in the two strings. e.g. (listne, listne), (Acte,etca)
Algorithm:
- check if the length of two strings s the same if not return false.
- if 1 is satisfied then check if the first character is equal to the first character of the second string then the second character with the second character of the second string and so on. If this condition does not satisfy then return false or return true
import java.util.Arrays; public class Main { private static boolean isAnagram(String a, String b) { // To Remove any spaces in the strings String c = a.replace(" ", "").toUpperCase(); String d = b.replace(" ", "").toUpperCase(); // Covert the strings to char array char[] e = c.toCharArray(); char[] f = d.toCharArray(); // sort the char arrays Arrays.sort(e); Arrays.sort(f); // if the strings are of different length then return false if (e.length != f.length) return false; // comparing each element of first char array with second element, if any // mismatch found then return false for (int i = 0; i < e.length; i++) { if (e[i] != f[i]) return false; } // if everything fine then return true return true; } public static void main(String[] args) { String a = "Listen "; String b = "Ilsent"; if (isAnagram(a, b)) { System.out.println("the string " + a.toUpperCase() + "is anagram
to string " + b.toUpperCase()); } else { System.out.println("the string " + a.toUpperCase() + "is NOT
anagram to string " + b.toUpperCase()); } } }
Output:
the string LISTEN is anagram to string ILSENT
The time complexity of the above program is O(nlogn)
Q2. Write a program to find the occurrence of each element in an array?
Suppose we have an integer array conatining the values {2,5,3,5,5,34,23,2,37} then we have to print the below output : 2:2, 3:1, 5:3, 23:1, 34:1, 37:1
Algorithm:
We will solve this problem with the help of map collection. We will treat the array elements as key and frequency as value for the map. Because each time we encounter the same element in the array its frequency will be replaced or updated with the new frequency value. This is the nature of the map interface.
- Create a map.
- we will run a loop till the size of the array.
- Inside the loop, we will check if the map contains the first element as a key then we will put the element in the map with the pre-existing value by calling map.get(arr[i]) method and add 1 to it.
- If the element is not present as a key then we will put the element as key and 1 as value, because this element is encountered the first time.
import java.util.HashMap; import java.util.Map; public class Main { public static void countFreq(int[] arr) { int size = arr.length; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // run a loop to iterate the array for(int i=0; i<size; i++) { // if map contains the element at ith index then update is frequency if(map.containsKey(arr[i])) { map.put(arr[i], map.get(arr[i])+1); } // else add the element as key and 1 as a frequency else { map.put(arr[i], 1); } } // print the map with lambda expression map.forEach((key,value) -> System.out.print(key+":"+value+" ")); } public static void main(String[] args) { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; countFreq(arr); } }
Output:
20:4 5:1 10:3
Time complexity and Auxilary space complexity of the above program is o(n)
The above problem can be solved by using java 8 stream api.
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class Main { public static void main(String args[]){ List<Integer> list = Arrays.asList(1,1,2,3,1,3,2,5,6); Map<Integer, Long> map= list.stream().collect(Collectors.
groupingBy(Function.identity(),Collectors.counting()));
map.forEach((x,y) -> System.out.println(x+"="+y)); } }
Q3. Write a program to sort words of a string separated by comma (,)?
The idea is to first split the string with the comma (,) delimiter and then add each word to a list. now we can apply the stream's sorted method to sort the words in natural alphabetical order and then we can collect them and we can use the joining method to add a comma (,) in between the words.
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // Input String String s = "hi,who,are,you,my,friend"; System.out.println("Before sorting -- " + s); // Split the string based on comma(,) String[] b = s.split(","); // add the tokens in a list one by one List<String> list = new ArrayList<>(); for (String string : b) { list.add(string); } // sort using stream's sorted method and use joining to add the "," in between // values String result = list.stream().sorted().collect(Collectors.joining(",")); System.out.println("After Sorting -- " + result); } }
Output:
Before sorting -- hi,who,are,you,my,friend After Sorting -- are,friend,hi,my,who,you
What will be the output of the below programs?
Q4.
public class A { public static void main(String[] args){ if (true) break; } }
Output: The above code will not compile because the Break statement can only be used with a loop or switch. So, using break with if statement causes “break outside switch or loop” error.
Q5.
public class A { public static void main(String[] args){ System.out.println('j' + 'a' + 'v' + 'a'); } }
Output: “java” would be printed if String literals (in double quotes) are used, but in the question, since character literals has been used, these won’t be concatenated. Therefore After execution of the program, an addition of each equivalent ASCII(Unicode) value of the character will be obtained.
Hence the output is 106 + 97 + 118 + 97 = 418
Q6.
class Main { public static void main(String args[]) { System.out.println(fun()); } int fun() { return 20; } }
Output: The above code snippet will not compile because here we are trying to call the fun() method without creating the object of the class. But it is a non-static method, so we must create an object or make the method static to access without creating an object.
Q7.
public class Main { public static void main(String args[]){ Point p = new Point(); System.out.println("x = " + p.x + ", y = " + p.y); } } class Point { protected int x, y; public Point(int _x, int _y){ x = _x; y = _y; } }
Output: It will not compile because we are not passing the parameters at the time of object creation.
Q8.
public class Main { public static void main(String args[]){ Point pnt1 = new Point(0,0); Point pnt2 = new Point(0,0); System.out.println("pnt1.X: " + pnt1.x + " pnt1.Y: " +pnt1.y); System.out.println("pnt2.X: " + pnt2.x + " pnt2.Y: " +pnt2.y); System.out.println(" "); swap(pnt1,pnt2); System.out.println("pnt1.X: " + pnt1.x + " pnt1.Y: " + pnt1.y); System.out.println("pnt2.X: " + pnt2.x + " pnt2.Y: " +pnt2.y); } public static void swap(Point arg1, Point arg2) { arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; } } class Point { protected int x, y; public Point(int _x, int _y){ x = _x; y = _y; } }
Output:
pnt1.X: 0 pnt1.Y: 0 pnt2.X: 0 pnt2.Y: 0 pnt1.X: 100 pnt1.Y: 100 pnt2.X: 0 pnt2.Y: 0
Q9. How to find the occurrences of the students of the same age in a map using java8?
// Java program for list convert in map // with the help of stream api of java8 import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.stream.Collectors; // create a list class Student { // age will act as Key private Integer age; // name will act as value private String name; // create constructor for reference public Student(Integer age, String name) { // assign the value of age and name this.age = age; this.name = name; } // return private variable id public Integer getAge() { return age; } // return private variable name public String getName() { return name; } } // main class and method public class Main { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(10, "Tapas")); lt.add(new Student(20, "Mishra")); lt.add(new Student(13, "Jak")); lt.add(new Student(13, "Jim")); LinkedHashMap<Integer, String> map = lt.stream().collect( Collectors.toMap(Student :: getAge, Student : getName,
(x, y) -> x + ", " + y, LinkedHashMap :: new)); // print map map.forEach((x, y) -> System.out.println(x + "=" + y)); } }
Q10. How to convert a list of strings in map using java8?
public class Main { // main Driver public static void main(String[] args) { // create a list List<String> lt = Arrays.asList("afe","Tapas","mishra","sf","sf"); Map<String, Integer> map = lt.stream().distinct().collect(Collectors.
toMap(s -> s, s -> 0)); // print map map.forEach((x, y) -> System.out.println(x + "=" + y)); } }
Output:
afe=0 sf=0 Tapas=0 mishra=0
If we are not including the distinct method and the list doesn't contain duplicates then it will work fine. But if in the list, we have duplicates and we are not using the distinct method, in that case, will get IllegalstateException at runtime.
Exception in thread "main" java.lang.IllegalStateException: Duplicate key sf (attempted merging values 0 and 0)
Q11. How can we create an immutable class with mutable objects?
See this article for a detailed explanation.
Q12.