Blog Encora

Interview At Encora Innovation labs

Question: How can you print the elements of a matrix in a spiral Order?

Answer: This Question is available in Leetcode

Spiral Matrix

https://leetcode.com/problems/spiral-matrix/description/
Java
package matrix;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class SpiralTravelOfMatrix {
    public static void main(String[] args) {
        int [] [] matrix = {{1,2,3, 4,5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}};
        List<Integer> path = printSpiral(matrix);
        String spiral = path.stream().map(number -> number.toString()).collect(Collectors.joining(","));
        System.out.println(spiral);
    }

    public static List<Integer> printSpiral(int [][] matrix){
        int row = matrix.length;
        int col = matrix[0].length;
        int colIndex = 0, rowIndex =0;
        List<Integer> spiralPath = new ArrayList<>();
        while (rowIndex< row && colIndex < col){
            for(int i=colIndex; i<col; i++){
                spiralPath.add(matrix[rowIndex][i]);
            }
            rowIndex++;

            for(int i=rowIndex; i<row; i++){
                spiralPath.add(matrix[i][col -1]);
            }
            col--;

            if(rowIndex < row){
                for(int i=col-1; i>=colIndex; i--){
                    spiralPath.add(matrix[row - 1][i]);
                }
            }
            row--;
            if(colIndex < col){
                for(int i=row -1; i>= rowIndex; i--){
                    spiralPath.add(matrix[i][colIndex]);
                }
            }
            colIndex++;
        }
        return spiralPath;
    }
}

The Common Mistake

The common mistake occurs in the third and fourth for-loops of the code, where we are supposed to traverse the matrix in reverse order. The condition in these loops should be i >= rowIndex and i >= colIndex respectively, not i >= col and i >= row.

Here’s the incorrect code:

Java
if(rowIndex < row){
    for(int i=col-1; i>=col; i--){
        spiralPath.add(matrix[row - 1][i]);
    }
}
row--;
if(colIndex < col){
    for(int i=row -1; i>= row; i--){
        spiralPath.add(matrix[i][colIndex]);
    }
}
colIndex++;

The Solution

The solution is to correct the conditions in the third and fourth for-loops. Here’s the corrected code:

Java
if(rowIndex < row){
    for(int i=col-1; i>=colIndex; i--){
        spiralPath.add(matrix[row - 1][i]);
    }
}
row--;
if(colIndex < col){
    for(int i=row -1; i>= rowIndex; i--){
        spiralPath.add(matrix[i][colIndex]);
    }
}
colIndex++;

Question: Print Primary Numbers which comes under number 50,

Question: Can you please tell me about how many types of exceptions in Java?



Question :Can we define our own custom exception?What is the type of this exception which you define? Checked or unchecked?

Yes, in Java, we can define our own exceptions. These are known as custom exceptions or user-defined exceptions. Custom exceptions can be either checked or unchecked, depending on the need.

To create a custom exception, we need to extend the Exception class. Here’s an example of a custom checked exception called IncorrectFileNameException:

Java
public class IncorrectFileNameException extends Exception {
    public IncorrectFileNameException(String errorMessage) {
        super(errorMessage);
    }
}

In this example, IncorrectFileNameException is a checked exception because it extends Exception. The constructor takes a string as the error message and passes it to the parent class constructor¹.

We can also create custom unchecked exceptions by extending the RuntimeException class. Here’s an example:

Java
public class CustomRuntimeException extends RuntimeException {
    public CustomRuntimeException(String message) {
        super(message);
    }
}

In this example, CustomRuntimeException is an unchecked exception because it extends RuntimeException.

The type of exception (checked or unchecked) you define depends on your specific needs. Checked exceptions are typically used for recoverable conditions and require a catch clause or a throws clause in the method signature. Unchecked exceptions are typically used for programming errors and do not require a catch or throws clause¹².

Question: Have you worked on collection?What type of collection frequently you are using?

Question: Which collection do you use and how you can retrieve the employee ID on the basis of these three parameters (name, father’s name, and date of birth)?

Question: Suppose if I want to sort this list of employee via date of birth, what do I need to do?

Question: Why we are using the lambda function? What is the benefit of that stream?

Question: How we can avoid concurrent modification exception?

The ConcurrentModificationException is thrown when one thread is iterating over a collection and another thread modifies that collection at the same time. Here are a few strategies to avoid this exception:

  1. Synchronized Block: You can use a synchronized block to ensure that the collection is only accessed by one thread at a time. However, this can lead to performance issues if many threads need to access the collection.
Java
synchronized(collection) {
    Iterator iterator = collection.iterator();
    while (iterator.hasNext()) {
        // ...
    }
}
  1. Concurrent Collections: Java provides thread-safe collection classes in the java.util.concurrent package such as ConcurrentHashMap, CopyOnWriteArrayList, etc. These collections are designed to handle concurrent access and modification.
Java
List<String> list = new CopyOnWriteArrayList<>();
// add elements
for (String item : list) {
    // ...
}
  1. Iterator.remove(): If you need to remove elements from a collection while iterating, use the Iterator.remove() method instead of Collection.remove(). This method is safe to use during iteration.
Java
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
    Object element = iterator.next();
    if (someCondition) {
        iterator.remove();
    }
}
  1. Avoid Modification: If possible, avoid modifying the collection while iterating. For example, you can collect the elements to be removed in a separate collection, and then remove them all at once after the iteration is complete.

Remember, the best approach depends on your specific use case and requirements. If you provide more details about your situation, I can give a more specific recommendation. 😊

Question:What is predicate?

Question: How can I implement this interface with a default method and an abstract method in Lambda expression?

In Java, a lambda expression can be used to provide the implementation of a functional interface, which is an interface with a single abstract method. However, if an interface has more than one abstract method, it cannot be represented as a lambda expression.

In your case, you have an interface with a default method and an abstract method. If the interface only has one abstract method, you can use a lambda expression to implement that abstract method. The default method is already provided in the interface and does not need to be implemented.

Here’s an example:

Java
public interface MyInterface {
    // Abstract method
    int add(int a, int b);

    // Default method
    default String add(String firstname, String lastname) {
        return firstname + " " + lastname;
    }
}

public class Main {
    public static void main(String[] args) {
        // Implement the interface using a lambda expression
        MyInterface myInterface = (a, b) -> a + b;

        // Use the lambda expression to call the abstract method
        int sum = myInterface.add(5, 3);
        System.out.println("Sum: " + sum);

        // Call the default method
        String fullName = myInterface.add("John", "Doe");
        System.out.println("Full Name: " + fullName);
    }
}

In this code, MyInterface is an interface with an abstract method add(int a, int b) and a default method add(String firstname, String lastname). The Main class implements MyInterface using a lambda expression (a, b) -> a + b, which provides the implementation of the add(int a, int b) method. The add(String firstname, String lastname) method is already provided in the interface and does not need to be implemented.

Please note that if MyInterface had more than one abstract method, it could not be represented as a lambda expression. In that case, you would need to create a class that implements the interface and provides implementations for all of its abstract methods. If you have any more questions about lambda expressions or interfaces, feel free to ask! I’m here to help. 😊

Question: I need employee ID of the second highest salary employee from a table with employee ID and salary columns. How can I get it?

It seems like you’re trying to find the employee ID of the employee with the second highest salary. However, the SQL query you’ve written seems to have a few errors. Here’s how you can correct it:

Java
SELECT employee_id, salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

In this query:

  • ORDER BY salary DESC sorts the employees in descending order of salary.
  • LIMIT 1 OFFSET 1 skips the first row (the highest salary) and returns the next row (the second highest salary).

This will give you the employee ID and salary of the employee with the second highest salary. If you only want the employee ID, you can remove salary from the SELECT clause.

Please replace employee_id and salary with your actual column names if they are different. Also, ensure that your table name is correct. In this query, I’ve used Employee as the table name as per your question.

Question: Before designing any API, what we need to consider?

  1. What is the difference in GET and POST methods?
  2. What about POST and PUT?
  3. What is the functionality of API Gateway when you are using in AWS?
  4. What is the meaning of Status code 401?
Avatar

Neelabh

About Author

As Neelabh Singh, I am a Senior Software Engineer with 6.6 years of experience, specializing in Java technologies, Microservices, AWS, Algorithms, and Data Structures. I am also a technology blogger and an active participant in several online coding communities.

You may also like

Blog Design Pattern

Understanding the Builder Design Pattern in Java | Creational Design Patterns | CodeTechSummit

Overview The Builder design pattern is a creational pattern used to construct a complex object step by step. It separates
Blog Tech Toolkit

Base64 Decode

Base64 encoding is a technique used to encode binary data into ASCII characters, making it easier to transmit data over