Showing posts with label interview questions. Show all posts
Showing posts with label interview questions. Show all posts

Thursday, May 5, 2022

ZOHO QUESTION : Given a 9×9 sudoku we have to evaluate it for its correctness.

Here we have some simplest way to check the sudoku validation. And we have few discussion and suggestion on this post comments section, so we decided to give the solution as per the discussion.

Coding snippet:

private static boolean check(){

    int[][] l_arrSudukoMatrix = new int[][] {
{ 5, 1, 3, 6, 8, 7, 2, 4, 9 },
{ 8, 4, 9, 5, 2, 1, 6, 3, 7 },
{ 2, 6, 7, 3, 4, 9, 5, 8, 1 },
{ 1, 5, 8, 4, 6, 3, 9, 7, 2 },
{ 9, 7, 4, 2, 1, 8, 3, 6, 5 },
{ 3, 2, 6, 7, 9, 5, 4, 1, 8 },
{ 7, 8, 2, 9, 3, 4, 1, 5, 6 },
{ 6, 3, 5, 1, 7, 2, 8, 9, 4 },
{ 4, 9, 1, 8, 5, 6, 7, 2, 3 } }; //valid

for(int i = 0 ; i < l_arrSudukoMatrix.length; i++){
int sumRow = 0;
int sumColumn = 0;
int col = 0;
for(int j = 0 ; j < l_arrSudukoMatrix.length; j++){
sumColumn += l_arrSudukoMatrix[i][j];
sumRow += l_arrSudukoMatrix[j][i];
col = j;
}
if(sumRow != 45 || sumColumn != 45){
System.out.println("invalid");
return false;
}
}
System.out.println("valid");
return true;
}


Output: valid

If you change input array to duplicate any value in row or column you will get output like this.

Input: 

int[][] l_arrSudukoMatrix = new int[][] {
{ 5, 1, 3, 6, 8, 7, 2, 4, 9 },
{ 8, 4, 9, 5, 2, 1, 6, 3, 7 },
{ 2, 6, 7, 3, 4, 9, 5, 8, 1 },
{ 1, 5, 8, 4, 6, 3, 9, 7, 2 },
{ 9, 7, 4, 2, 1, 8, 3, 6, 5 },
{ 3, 2, 6, 7, 9, 5, 4, 1, 0 }, //0 is not a valid one.
{ 7, 8, 2, 9, 3, 4, 1, 5, 6 },
{ 6, 3, 5, 1, 7, 2, 8, 9, 4 },
{ 4, 9, 1, 8, 5, 6, 7, 2, 3 } };

Ouput: Invalid


Thank you.

Friday, April 22, 2022

Coding interview questions: Python

Hello, 

Here in this post I will solve some basic coding interview question. This time I used python. Yes its cool.

Find second largest number in given array?

input: [1,2,0,9,8] output: 8
input: [0,1,-1,-2] output: 0
input: [3] output: 
input: [] output: 
def findSecondLargestNumber(arr_list):
  largest = None
  secondL = None
  for i in arr_list:
    if largest == None:
      largest = i
    elif i > largest:
      secondL = largest
      largest = i
    elif secondL == None:
      secondL = i
    elif i > secondL:
      secondL = i
    
  print(secondL)

findSecondLargestNumber([0-11])

Find given two string inputs are reverse?
input: "ABC", "CBA" Output : True
input: "ABC", "cBA" Output : False
input: "ABC", "BCA" Ouput: False

def stringReverse(string1string2):
  for i in range(len(string1)):
    i1 = len(string2) - i -1;
    if(string1[i] != string2[i1]):
      return False
  return True 

stringReverse('ABC''cba')

Find given two string number, first input is greater than 2nd without using (int) convert?

Input: "1234" "4321" Ouput: False
Input: "1234" "321" Ouput: True
Input: "1234" "1234" Ouput: False

def largerthan(str1str2):
  if(len(str1) == len(str2)):
    for i in range(len(str1)):
      if str1[i] == str2[i]:
        continue
      elif str1[i] > str2[i]:
        return True
      else:
        return False
    return False
  elif len(str1) > len(str2):
    return True
  else:
    return False

largerthan('723''234')

Find rooks are safe in chessboard, if u don't know what is that? Don't worry, in chessboard rook can move vertical and horizontal line, if any rook block this we then moving rook will kill that?

For testing purpose I am using 4*4 board input instead of 8*8
Input: [[1,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,1]] Output: True
Input: [[1,0,0,0],[0,1,0,0],[0,1,0,0],[0,0,0,1]] Output: False (because array[1,1] and array[2,1] are in same vertical line,
so the rooks are not safe)

def rookSafe(arr):
  for i in range(len(arr)):
    countRow = 0;
    countCol = 0;
    for j in range(len(arr)):
      countRow += arr[i][j]
      countCol += arr[j][i]
      if countCol > 1 or countRow > 1:
        return False
  return True

rookSafe([[1,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,1]])


Java solution will be post soon!!👀

Thank you.

Wednesday, March 30, 2022

Interview Question: Sub String Palindrome using java.

Recent day interviews you may faced this question in programing interview. Find the sub string palindrome of given string input.

We have many way to solve it. Here I added coding snippet which I tried to solve it.

First one I used two for loop to solve it. Its very simple and easy.


private static List<String> subStringPalindrome(String value) {
List<String> list = new ArrayList<>();
for(int i =0 ; i < value.length(); i++){
for(int j = i+1 ; j < value.length(); j++){
StringBuffer s1 = new StringBuffer(value.substring(i,j));
String s2 = s1.reverse().toString();
if(value.substring(i,j).contentEquals(s2) && s1.length()> 1){
list.add(s1.toString());
}

}
}
return list;
}
List<String> list = subStringPalindrome("eetestseeammadam");
Output: [ee, ete, estse, sts, ee, amma, mm, ada]
Its very simple and easy. This code look simple and easy  and I tried another way using recursion.

private static List<String> printPalindromeSubString(String value;) {
List<String> list = new ArrayList<>();
if(value.equals(new StringBuilder(value).reverse()))
list.add(value);
for(int i=0; i <= value.length(); i++){
if(i > 1 && i < value.length() -1){
StringBuffer reverse = new StringBuffer(value.substring(i-2, i+1));
if(value.substring(i-2, i+1).contentEquals(reverse.reverse())){
System.out.println("Called2");
list.add(value.substring(i-2, i+1));
if(i>2){
if(i+2 <= value.length()){
new Test().callRecursion(value,value.substring(i-2, i+1), i-1, i, list );
}
}
}
}
if(i > 0 && i < value.length() ){
StringBuffer stringBuffer = new StringBuffer(value.substring(i-1, i+1));
if(value.substring(i-1, i+1).contentEquals(stringBuffer.reverse())){
list.add(value.substring(i-1, i+1));
System.out.println("Called");
if(i > 1){
new Test().callRecursion(value,value.substring(i-1, i+1), i, i, list );
}
}
}
}
return list;
}

private List<String> callRecursion(String value, String reversed, int i, int j, List<String> list){
if(j+1 >= value.length())
return list;
else if(value.charAt(i-2) == value.charAt(j+1)){
String s = value.charAt(i-2) +reversed+ value.charAt(j+1);
list.add(s);

callRecursion(value, s, i-1, j+1, list);
}
System.out.println(list);
return list;
}
List<String> list = printPalindromeSubString("eetestseeammadam");
Here i used recursion to find palindrome on given substring. And the output is 
[ee, ete, sts, estse, ee, mm, amma, ada, madam]

And the output is  If you check the output from two logic, there is a mismatch.. First one print only 8 palindrome and recursion logic print 9 palindrome. 'madam' missing in first logic. 
Lets make this blog more interactive with techies, Please find the missing condition or part of code on comment area.✌✌ 

Thanks in advance.

Wednesday, March 16, 2022

Lambda expression in java.

In this post we will going to discuss about what is lambda expression in java?. How to use them?. How it helps developers?. All this question will be answered end of this post.

Before we start answering this question, let we look in to some implementation to get 10+years experience employee from list of employee object.

Here coding snippet: 


public class Employee {


private int id;
private String name;
private double experience;
private long salary;
private int rating;

public Employee(int id, String name, double experience, long salary, int rating) {
this.id = id;
this.name = name;
this.experience = experience;
this.salary = salary;
this.rating = rating;

    }

    //Getter and Setter here

 }  

Here my implementation class to print 10+years experience employee. 


public static void main(String[] args) {
Employee employee1 = new Employee(5, "Antwaun", 5.5, 10000L, 1);
Employee employee2 = new Employee(2, "Rick", 32.5, 2000L, 3);
Employee employee3 = new Employee(1, "Richard", 50, 3000L, 4);
Employee employee4 = new Employee(3, "Corey", 22.5, 20000L, 2);
Employee employee5 = new Employee(4, "Chumlee", 10.5, 15000L, 5);

List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
employeeList.add(employee4);
employeeList.add(employee5);

printEmployeeExpGreaterTenYears(employeeList);
}
public static void printEmployeeExpGreaterTenYears(List<Employee> employeeList){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10){
System.out.println(employee);
}
}
}

Output:
Employee{id=2, name='Rick', experience=32.5, salary=2000, rating=3}
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=3, name='Corey', experience=22.5, salary=20000, rating=2}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}

This looks good. we are iterating list and check the experience grater or equals to 10. If in future the requirement change like we need to get 10+ experience and rating will be more than 4+. So then we need to change the existing logic or else we need to write a new method with two param. 

Let see the implementation,
public static void printEmployeeExpGreaterTenYearsAndSalaryPassed(
List<Employee> employeeList, int rating){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10 && employee.getRating() >= rating){
System.out.println(employee);
}
}
}

These condition may be change in future. Like employee salary, employee name or we may add some new variable in Employee class. So its not good to change existing logic or add new logic when we have new enhancement to be implement. 
So what else we can do?? .. Let think about Functional Interface in java 8. 
  • Functional interface, which have only one abstract method and any number of default method.
Let we create a Function interface with one abstract method. Interface name CheckEmployee for now have method name test(). 

public interface CheckEmployee {
boolean test(Employee employee);
}

Here we need to implement this test method, so I have created CheckEmployeeService class.
public class CheckEmployeeService implements CheckEmployee {
@Override
public boolean test(Employee employee) {
return (employee.getExperience() >= 10 && employee.getRating() >= 4);
}
}
Let add a method to printEmployee in out Impl class.
public static void printPersons(
List<Employee> employeeList, CheckEmployee checkEmployee){
for(Employee employee: employeeList){
if(checkEmployee.test(employee)){
System.
out.println(employee);
}
}
}
Now we can call this printPersons method from main method, 
printPersons(employeeList, new CheckEmployeeService());
Output:
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}

Its looks good. but we have created a Interface and Service class, that's not necessary we can create them inside the Impl class itself.

As already said CheckPerson interace is Functional interface. Because it has one and only abstract method. Java provide lambda operation for functional interface. We can use lambda expression on functional interface.
Let see how we can use them,

printPersons(employeeList, new CheckEmployeeService());
System.out.println("Lambda expression ");
printPersons(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
Output: 
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}
Lambda expression 
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}
Now you might get idea of how do we use lambda expression in java 8. In Functional interface we can use lambda expression. By using lambda expression it reduces the coding effort. Java provide many Functional interface, they all available in java.util.function 
For example we can use you can use the Predicate<T> interface in place of CheckEmployee. This interface contains the method boolean test(T t).
Let see how to use predicate interface instead of CheckEmployee.
public static void printEmployeesWithPredicate(
List<Employee> roster, Predicate<Employee> tester) {
for (Employee p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
call from main method, 
printEmployeesWithPredicate(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
This will print the same output ass like what we have printed by using CheckEmployee interface. So far we have answered what is lambda expression, how to use them and how it helps developer to reduce the coding effort. I hope this will give some basic and deep understanding of lambda expression. 
There are lot of Functional interface we have in java. Please go through the JavaDoc . So When we are speaking about lambda expression you might think of Steams.. Are you??. Okay. Let see how to we use Stream to printPersion.

Classes to support functional-style operations on streams of elements,
such as map-reduce transformations on collections. - JavaDoc .

Stream support functional style operation on stream element. Let we use stream element to printPersons. Here code snippet.
employeeList
.stream()
.filter(
employee -> employee.getExperience() >= 10 && employee.getRating() >= 4)
.forEach(employee -> System.out.println(employee));
This will print the same output ass like what we have printed by using CheckEmployee interface.

I hope this will give some basic and deep understanding of lambda expression and stream.  

Thank you all.
Consolidated Coding snippet.
package com.example.monitoring.lambda;

import com.example.monitoring.compare.CheckEmployee;
import com.example.monitoring.compare.CheckEmployeeService;
import com.example.monitoring.compare.Employee;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class EmployeeServiceImpl {

public static void main(String[] args) {
Employee employee1 = new Employee(5, "Antwaun", 5.5, 10000L, 1);
Employee employee2 = new Employee(2, "Rick", 32.5, 2000L, 3);
Employee employee3 = new Employee(1, "Richard", 50, 3000L, 4);
Employee employee4 = new Employee(3, "Corey", 22.5, 20000L, 2);
Employee employee5 = new Employee(4, "Chumlee", 10.5, 15000L, 5);

List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
employeeList.add(employee4);
employeeList.add(employee5);

printEmployeeExpGreaterTenYears(employeeList);
printPersons(employeeList, new CheckEmployeeService());
System.out.println("Lambda expression ");
printPersons(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
printEmployeesWithPredicate(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);

employeeList
.stream()
.filter(
employee -> employee.getExperience() >= 10 && employee.getRating() >= 4)
.forEach(employee -> System.out.println(employee));
}

public static void printEmployeeExpGreaterTenYears(List<Employee> employeeList){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10){
System.out.println(employee);
}
}
}

public static void printEmployeeExpGreaterTenYearsAndSalaryPassed(
List<Employee> employeeList, int rating){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10 && employee.getRating() >= rating){
System.out.println(employee);
}
}
}
public static void printPersons(
List<Employee> employeeList, CheckEmployee checkEmployee){
for(Employee employee: employeeList){
if(checkEmployee.test(employee)){
System.out.println(employee);
}
}
}

public static void printEmployeesWithPredicate(
List<Employee> roster, Predicate<Employee> tester) {
for (Employee p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}


}

Tuesday, March 1, 2022

Immutable String in Java.

This is very popular interview question in core java interview. Most of us will answer it, String is immutable. When the question is goes why String is immutable, few of us only answer it, due to misunderstanding of immutable.

Here we will discuss about why?.

Immutable is,  once a string object created in string pool or heap we cannot change the value of it. But we can change the value of the reference. That's what we are doing in below code.

String name = "Boomi";
name = "raj";

But we are able to change it right??. Its not what immutable means. Immutable means we cannot edit the "Boomi" from string pool. Let see how above string stored in java memory.

When we create name = "Boomi"value "Boomi" will be create in string pool and assigned this value to name reference.


When we reassign the value "raj" to name. "raj" value will be created in string pool and this value is referred to name variable. But still "Boomi" value is there in string pool and reference to name is removed. This is why string is called immutable.

Now you may have a question why java engineers made string as immutable. 

Let see an example to understand why string immutable? 

String name = "Boomi";
String userName = "Boomi";

Here we are creating two string with same name. If String is mutable then we need to create two time value "Boomi". So it might consume lot of memory for real time application. 

Another reason for String immutability is security. 


Let change name value to "Boomiraj".

name = "Boomiraj";



New Object will be created for "Boomiraj" this referred to name variable. userName still referring to the "Boomi".

We know we can create String object two ways, 

  • by using "". eg String name = "Boomi"; //Object stored in string pool
  • by using new. eg String userName = new String("Boomi");//Object stored in heap memory.
String name = "Boomi";
String userName = "Boomiraj";
String nameObj = new String("Boomi");
String userNameObj = new String("Boomiraj");




Let check the both name and userName not pointing to same object by using ==

System.out.println(name == nameObj); //false
System.out.println(userName == userNameObj);//false

Null Pointer Exception in Java

Here we will discuss about what is nullpointerexception and how to fix it?

In java if a variable or object reference do not have any value to assign to them , then we will have possibility of having null pointer exception. More clearly if a reference variable or object is assigned to nothing. For example,

public class NullPointerException {
public static void main(String[] args) {
Employee employee = null;
employee.getName();
}
}

Lets run this program, we are getting exception says below.,

Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:8)
Here we are trying to call getName() of employee object, but we did not create a object for it.  Which mean employee is referred to nothing . 

How to fix this issue, we need to create a new employee object using new Employee().After changing null to this we will not get exception. We are not assigned any value to employee name variable, even we don't get any exception, because we have not call any further from getName(). Let me modified something from above example,

public class NullPointerException {
public static void main(String[] args) {
Employee employee = new Employee();
employee.getName().length();
}
}

While running the main method we will get below exception
Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:8).

How to fix this issue, before we fix it, let we check other possible ways of having null pointer exception.

public class NullPointerException {
public static void main(String[] args) {
List<Employee> employeeList = null;
for(Employee employee1 : employeeList){
System.out.println(employee1);
}
}
}
Here we will get nullpointerexception on for loop, because we are trying to iterate from nothing.

List<Employee> employeeList = null;
Employee employee = new Employee();
employeeList.add(employee);
for(Employee employee1 : employeeList){
if(employee1.getName().equals("Boomiraj")){
System.out.println("Hello Boomiraj");
}
}

We will get exception on if condition to check equals(), because we do not set name to the employee object, so employee1 will have null on name variable. 

public static void main(String[] args) {
Employee employee = new Employee();
getEmployeeNameLength(employee);
}

public static int getEmployeeNameLength(Employee employee){
return employee.getName().length();
}

Here we will get exception on return statement of getEmployeeNameLength , here the exception trace will be like this and more details on it, 


Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.getEmployeeNameLength(NullPointerException.java:15)
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:11)

We have seen all the possible ways of having nullpointerexception. Let see how to fix them.

Never assign object reference to null, just initialize them new Employee();. We may have some scenarios to have dynamic object, there we cannot initialize object. we can handle them with condition check using null. let see above code we are trying to get length of the name from employee object. 

We need to check the getName is null or not before we call .length(). Before call getName() we need to check employee object itself null or not.

public static int getEmployeeNameLength(Employee employee){
if(employee != null &&
employee.getName() != null)
{
return employee.getName().length();
}
return 0;
}
Above code might be looks like ugly code, we don't have any other option to check it.

On employee name equals check we need to pass static value first then we need to check equality.

if("Boomiraj".equals(employee.getName())){
System.out.println("Hello Boomiraj");
}

For loop fix we need initialize the list object.
List<Employee> employeeList = new ArrayList<>();

Now we have fixed all the possible ways of null exception. 

But this could not be happen to primitive type. Because we cannot declare a primitive type as null, primitive types always have their default value. Lets try with example.

Boolean isNull = null;
if(isNull){
System.out.println("Its null!");
}
 Lets try with example. Here I used Boolean wrapper class. So we can assign null to it, but if we use primitive boolean we cannot assign null to it. 

boolean isNull = null; 
Here I am getting compilation error says, required type boolean, provider null.
If you have possible way to declare primitive type, use them to rid out of nullpointerexception.

Thank you!.

Thursday, February 24, 2022

How to Check if an Array Contain Duplicate In Java?

Hello All, 

Here the coding snippet to check duplicate in array. I used char[] to check the duplicate character check in a string. 


private static void findDuplicate(String input){
char[] strChar = input.toCharArray();
boolean haveDuplicate = false;
for(int i = 0 ; i < input.length(); i++){
for(int j = i+1 ; j < input.length(); j++){
if(strChar[i] == strChar[j]){
haveDuplicate = true;
System.out.print(strChar[i]);
}
}
}
if(!haveDuplicate){
System.out.println("No duplicate found in array");
}
}
Let pass input as "Java".
Output : a

Pass input as "Python"
Output : No duplicate found in array

Tuesday, February 22, 2022

SecurityContext and SecurityContextHolder in Spring Security.

Main purpose of SecurityContext to hold the currently authenticated user information as
principal and make sure this principal will be available all the method in same thread.
To get authenticated user details SecurityContextHolder will be used.


from principle? Here my spring boot project structure. From this principal we can get the currently logged in user. How can we get the user detail.



I have added spring-boot-starter-security jar in my pom.xml. This to set a default login screen for my application. 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If you add this dependency, spring boot will generate the password for your application on
server startup.

You can see the password in console log: Here generated security is below and default username will be 'user',
Using generated security password: e3660fc9-941c-4012-ba6d-8d1870a177d6. If you restart the server then new password will be generate.

Let we check the principal for default user and password for security context.



Here we are able to get the username of currently logged in user using securitycontext and securitycontextholder. 

We cannot every time copy the password from console. Spring provide the properties to set username and password. Here I used them for my application security. Let we check principal after change this property change.

spring.security.user.name=username
spring.security.user.password=User@123

Let login the application using new username and password, check the securityContext 
userdetails,




Let check with other method call and find the username for securitycontext.
let me call my getUser() to fetch particular user detail from db,

let me call : http://localhost:8084/getUser?userId=101

Here we can see the username from securityContext. Usually we need to have
securityContextHolder to get securityContext, from securityContext we can get authentication
from there we can get principal.

Here code snippet:

Object principalObject = SecurityContextHolder.getContext().
                                    getAuthentication().getPrincipal();

if(principalObject instanceof org.springframework.security.core.userdetails.User)
{
String userName = ((org.springframework.security.core.userdetails.User)principalObject)
                                                                               .getUsername();
System.out.println("logged in user: " + userName);
}

Main purpose of SecurityContext to hold the currently authenticated user information as
principal and make sure this principal will be available all the method in same thread.
To get authenticated user details SecurityContextHolder will be used.


From this principal we can get the currently logged in user. How can we get the user detail
from principle? Here my spring boot project structure.