Showing posts with label Java example. Show all posts
Showing posts with label Java example. Show all posts

Tuesday, 21 March 2023

Check for Balanced Brackets in an expression (well-formedness) Input: exp = “[()]{}{[()()]()}” in Java

Introduction:

In computer science, balanced parentheses are important to check the syntax of an expression. An expression is considered balanced when every opening parenthesis has a corresponding closing parenthesis, and they are in the correct order. In this blog post, we will discuss how to check for balanced brackets in an expression in Java.


Algorithm:

To check for balanced brackets in an expression, we can use a stack data structure. We will traverse the expression from left to right and push every opening bracket onto the stack. When we encounter a closing bracket, we will pop the topmost element from the stack and compare it with the closing bracket. If the brackets match, we continue with the traversal; otherwise, we return false, indicating that the expression is not balanced. After completing the traversal, if the stack is empty, we return true; otherwise, we return false.


Let's look at the code for the same.


Java Code:



import java.util.*;


public class BalancedBrackets {

   public static boolean isBalanced(String expression) {

      Stack<Character> stack = new Stack<Character>();

      for (int i = 0; i < expression.length(); i++) {

         char ch = expression.charAt(i);

         if (ch == '(' || ch == '{' || ch == '[') {

            stack.push(ch);

         } else if (ch == ')' || ch == '}' || ch == ']') {

            if (stack.isEmpty()) {

               return false;

            } else if (ch == ')' && stack.peek() == '(') {

               stack.pop();

            } else if (ch == '}' && stack.peek() == '{') {

               stack.pop();

            } else if (ch == ']' && stack.peek() == '[') {

               stack.pop();

            } else {

               return false;

            }

         }

      }

      return stack.isEmpty();

   }


   public static void main(String[] args) {

      String expression = "[()]{}{[()()]()}";

      if (isBalanced(expression)) {

         System.out.println("The expression is balanced.");

      } else {

         System.out.println("The expression is not balanced.");

      }

   }

}

Explanation:

In this code, we have defined a method named isBalanced, which takes a String expression as input and returns a boolean value indicating whether the expression is balanced or not.


We have used a stack data structure to keep track of the opening brackets. We traverse the expression from left to right and push every opening bracket onto the stack. When we encounter a closing bracket, we pop the topmost element from the stack and compare it with the closing bracket. If the brackets match, we continue with the traversal; otherwise, we return false, indicating that the expression is not balanced. After completing the traversal, if the stack is empty, we return true; otherwise, we return false.


In the main method, we have created a String expression and called the isBalanced method to check whether the expression is balanced or not.


Conclusion:

In this blog post, we discussed how to check for balanced brackets in an expression in Java. We used a stack data structure to keep track of the opening brackets and compared every closing bracket with the topmost element of the stack. If the brackets matched, we continued with the traversal; otherwise, we returned false. Finally, we checked whether the stack was empty or not to determine whether the expression was balanced or not.

Most popular coding interview question on LinkedList

 Introduction:

Welcome to this blog where we will discuss the popular coding interview question on LinkedList. LinkedList is one of the most common data structures used in programming, and its implementation can be found in almost every programming language. In this blog, we will go through a common LinkedList question and its answer that can help you prepare for your next coding interview.


Question:

Given a LinkedList, write a function to reverse it.


Solution:

To reverse a LinkedList, we need to reverse the direction of all the pointers. We can do this by iterating through the list and updating the pointers to point in the opposite direction. Here is the step-by-step approach to reverse a LinkedList:


Create three pointer variables: previous, current, and next. The previous pointer will initially be null, and the current pointer will point to the head of the LinkedList.


Traverse through the LinkedList, updating the next pointer to the current node's next node and then updating the current node's next pointer to the previous node.


Move the previous pointer to the current node and move the current node to the next node.


Repeat steps 2 and 3 until the end of the LinkedList is reached.


Set the head pointer of the LinkedList to the previous pointer.


Here is the implementation of the above approach:



class LinkedListNode {

  constructor(value) {

    this.value = value;

    this.next = null;

  }

}


function reverseLinkedList(head) {

  let previous = null;

  let current = head;

  let next = null;


  while (current != null) {

    next = current.next;

    current.next = previous;

    previous = current;

    current = next;

  }


  return previous;

}

In the above implementation, we first initialize the three pointers to null or the head of the LinkedList. Then we traverse through the LinkedList and update the pointers' values. Finally, we set the head pointer of the LinkedList to the previous pointer, which will be the last node of the original LinkedList.


Conclusion:

In this blog, we have discussed a common LinkedList question and its solution. Reversing a LinkedList is a popular question asked in coding interviews, and its implementation can be found in almost every programming language. By understanding the above approach, you can easily solve this problem and ace your coding interview.

Sunday, 12 March 2023

Experience Interview Question and Answer on Java Stream API

 Introduction:

Java Stream API is a powerful feature introduced in Java 8 that provides a functional programming style for processing collections of data. In this article, we will discuss some experience interview questions related to Java Stream API and provide answers to help you prepare for your next interview.


Question 1: What is the difference between a Stream and a Collection in Java?

Answer: A Collection is a data structure that holds a group of objects, whereas a Stream is a sequence of objects that can be processed in a functional style. Collections are typically used for storing and retrieving data, while Streams are used for processing and transforming data.


Question 2: What are the benefits of using Java Stream API?

Answer: Java Stream API provides several benefits, including:


Simplifies processing of large data sets

Enables parallel processing for improved performance

Provides a functional programming style for more concise and expressive code

Supports lazy evaluation, which reduces memory usage and improves performance

Question 3: What is the difference between intermediate and terminal operations in Java Stream API?

Answer: Intermediate operations are operations that transform a Stream into another Stream, while terminal operations are operations that produce a result or a side-effect. Intermediate operations include operations like filter(), map(), and sorted(), while terminal operations include operations like forEach(), collect(), and reduce().


Question 4: How do you convert a Stream to a List in Java?

Answer: To convert a Stream to a List in Java, you can use the collect() method with the Collectors.toList() method, as shown below:


List<String> list = stream.collect(Collectors.toList());


Question 5: What is lazy evaluation in Java Stream API?

Answer: Lazy evaluation is a technique used in Java Stream API that postpones the evaluation of an operation until it is actually needed. This allows for more efficient use of memory and can improve performance. Lazy evaluation is supported by intermediate operations in Stream API.


Conclusion:

Java Stream API is a powerful feature that provides a functional programming style for processing collections of data. In this article, we discussed some experience interview questions related to Java Stream API and provided answers to help you prepare for your next interview. By understanding these concepts and practicing with Java Stream API.

Exploring the New Features in Java 8

 Introduction:

Java 8, released in 2014, introduced several new features and improvements to the Java programming language. In this article, we will explore some of the major features of Java 8.


Lambda Expressions:

Lambda expressions are one of the most significant features of Java 8. They enable functional programming style in Java by providing a concise way of representing anonymous functions. Lambda expressions are essentially a way to pass behavior as a method argument.


For example, consider the following code snippet that uses a lambda expression to sort a list of integers:


List<Integer> numbers = Arrays.asList(5, 2, 7, 1, 9);

Collections.sort(numbers, (a, b) -> a.compareTo(b));


Here, we pass a lambda expression as the second argument to the sort() method, which compares two integers and returns the result.


Stream API:

The Stream API is another major feature of Java 8. It allows you to process collections of objects in a functional way. The Stream API provides a set of operations like filter, map, reduce, and more. These operations can be used to transform, filter, and aggregate data in a declarative way.


For example, consider the following code snippet that uses the Stream API to filter and map a list of strings:


List<String> words = Arrays.asList("hello", "world", "java");

List<String> filteredWords = words.stream()

.filter(s -> s.startsWith("j"))

.map(String::toUpperCase)

.collect(Collectors.toList());


In this code, we use the filter() method to filter out the strings that do not start with the letter 'j', then use the map() method to convert the filtered strings to upper case, and finally use the collect() method to collect the results into a new list.


Date and Time API:

Java 8 introduced a new Date and Time API that provides a more comprehensive and flexible way of handling dates and times. The new API provides classes like LocalDate, LocalTime, LocalDateTime, and more, which are immutable and thread-safe.


For example, consider the following code snippet that uses the new Date and Time API to create a date and time object:


LocalDateTime now = LocalDateTime.now();


This code creates a new LocalDateTime object that represents the current date and time.


Optional Class:

The Optional class is another useful feature introduced in Java 8. It provides a more elegant way of handling null values. The Optional class is essentially a container object that may or may not contain a non-null value.


For example, consider the following code snippet that uses the Optional class to avoid null pointer exceptions:


String name = getName();

Optional<String> optionalName = Optional.ofNullable(name);

String defaultName = "John Doe";

String finalName = optionalName.orElse(defaultName);


In this code, we use the ofNullable() method to create an Optional object that may or may not contain a non-null value. We then use the orElse() method to provide a default value in case the Optional object is empty.


Conclusion:

Java 8 introduced several new features and improvements that make Java programming more expressive, concise, and flexible. In this article, we explored some of the major features of Java 8, including lambda expressions, the Stream API, the Date and Time API, the Optional class, and more. These features have made Java a more powerful and modern programming language