How to remove duplicate(s) from linked list in Java? Example Tutorial

Hello guys, if you are wondering how to find duplicates in a given linked list in Java then you have come to the right place. In the past, I have explained how to reverse a linked list in Java, find kth element from tail in linked list, find cycle on linked list, and in this article, I will show you how to find duplicate nodes in a given linked list. This is one of the classic linked list coding problem and I have also included this in my list of 30 common linked list problems for programmers. You can further check that list to practice more linked list programs and improve your understanding of linked lists and how to solve those problems. But, before we get into details of finding and printing duplicate nodes from the given linked list let's start with the basics. 

How to find Factorial in Java using Recursion and Iteration - Example Tutorial

Hello guys, if you are looking for a Java program to calculate factorial with and without recursion then you have come to the right place. Factorial is a common programming exercise that is great to learn to code and how to program. When I teach Java to new people, I often start with coding problems like prime numbers, Fibonacci series, and factorial because they help you to develop a coding sense and teach you how to write a program initially. In order to calculate factorial, you just need to know the factorial concepts from Mathematics, and rest I will explain this simple Java programming tutorial. 

How to calculate perimeter and area of square in Java? Example Tutorial

If you are looking for a solution of problem how to calculate perimeter and area of a given Square in Java then you have come at the right place. In this article, I have given step by step solution of this common coding problem. This was actually a homework exercise when I was learning Java program and since I was good at Maths, I know how to calculate Perimeter and Area of Circle and Square but big challenge for me was to convert that knowledge into code. Another big challenge for me was how to take input from user actually that was the mistake I made when I first solved this problem. 

How to solve word break problem in Java using dynamic programming? Example

Problem Statement:
You are given a dictionary of words and the input string. Determine input string can be segmented into a space-separated sequence of given dictionary words.

Note: This question is based on dynamic programming and asked multiple times in top product-based companies.

Inputs:

         Dict = {i, like, am, boy, e, o, dog, cat, g};

        word = "iIikedog"  --------can be segmented into space-separated words--------> i, like, dog




Ask yourself that 'I', 'like', and 'dog' are presented in the dictionary?

Yes, so we can say that the given string can be segmented.

Now let's take another example.

         word = "ilikecatsanddog" --------- can be segmented as-----> i, like, cats, and, dog

                                                                                                              i, like, cat, s, and, dog

We can see that the words 'cats', 'and', 's' are not present in the dictionary so such a string can't be segmented into space-separated words.



Let's try to solve it.....

Like another dynamic programming problem, we will create a matrix and will use previously calculated results to calculate the current result.


Consider the given string as an array like this.

i

l

i

k

e

d

o

g

 

The columns and rows represent the same given string in the matrix.



Now let's try to understand what each cell represents in the matrix.

The cells can have two kinds of values either '0' or '1'. Suppose the cells (3,6) and (3,7) have the value '1' this means the substrings from 3 to 6 and 3 to 7 are present in the given input dictionary.


If you notice the cell (5,3) and the corresponding substring in the given word the direction is reverse and there is no point in considering the reverse computation of the given string. So we will mark all such cells as '0'.

We filled half of the matrix with value '0' so we no need to perform the reverse computations for these cells. This way we can save both memory and time.

Now start filling rest of the cells manually by comparing the row-column pair value against the given dictionary.

So the cell (0, 0) i.e. 'i' is present in the dictionary so matrix[0][0] = 1.

Similarly cell (4, 4) i.e. 'e' is also present in the dictionary so matrix[4][4] = 1.

Now let's take one substring 'ilike' and see the logic to solve this problem.

i

l

i

k

e

d

o

g

0

1

2

3

4

5

6

7


          

          i      l     i     k      e

          0     1    2    3      4


We will try to separate this string into 2 parts in all the possible ways.

Let say we have first 2 parts: 

(0, 0)--------> 'i' and (1, 1)----------> 'l' 

matrix[0][0] && matrix[1][1]

                  1 && 0

So 'il' is not present in the dictionary.

Consider another combination.

(4, 3)--------> 'k' and (4, 4)----------> 'e' 

matrix[4][3] && matrix[4][4]

                  0 && 1



This is false means 'ke' is not present in the dictionary.

So I will keep on taking the substrings from the given word to be space separated and divide them into 2 parts in different ways and will check against the matrix that if both the parts are true i.e. '1' means the substring is present in the dictionary.


So finally we will consider the entire given word and divide it into 2 parts in all the possible ways and we will use the values of the previously computed cells to calculate the value of the marked cell and if the the value is '1' means the given word can be separated into the space separated segments.

Start Implementing it...

Consider below code snippet.

i

l

i

k

e

d

o

g

0

1

2

3

4

5

6

7



       For i = 0 and N = 7


      for(int k = 0; k < N+1; k++){



              if(matrix[i][i+k]) && matrix[k+1][N])

              {

                    return true;

              }

     }


The if condition shows the logic to divide the given word into 2 parts in all possible ways.


Complete Code:

public class Main {

   

    public String wordBreakProblem(String word, Set<String> dict){

            int matrix[][] = new int[word.length()][word.length()];

            

// fill all the cells with '-1'.

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

                for(int j=0; j < matrix[i].length ; j++){

                    matrix[i][j] = -1; 

                }

            }

            

            

//If the substring is present in the dictionary then fill the corresponding cell with non-negative value.

            for(int l = 1; l <= word.length(); l++){

                for(int i=0; i < word.length() -l + 1 ; i++){

                    int j = i + l-1;

                    String str = word.substring(i,j+1);

                    

                    if(dict.contains(str)){

                        matrix[i][j] = i;

                        continue;

                    }

                    

// Filling the value of the corresponding cell for the taken substring using value of the previously calculated cell.

                    for(int k=i+1; k <= j; k++){

                        if(matrix[i][k-1] != -1 && matrix[k][j] != -1){

                            matrix[i][j] = k;

                            break;

                        }

                    }

                }

            }

            if(matrix[0][word.length()-1] == -1){

                return null;

            }

            

            

//Finally segregate the given word into the words available in the dictionary.

            StringBuffer buffer = new StringBuffer();

            int i = 0; int j = word.length() -1;

            while(i < j){

                int k = matrix[i][j];

                if(i == k){

                    buffer.append(word.substring(i, j+1));

                    break;

                }

                buffer.append(word.substring(i,k) + " ");

                i = k;

            }

            

            return buffer.toString();

        }

        public static void main(String args[]){

            Set<String> dictionary = new HashSet<String>();

            dictionary.add("I");

            dictionary.add("like");

            dictionary.add("had");

            dictionary.add("play");

            dictionary.add("to");

            String str = "Ihadliketoplay";

            Main bmw = new Main();

            String result1 = bmw.wordBreakProblem(str, dictionary);

            

            System.out.print(result1);

        }

    }


Output:

I had like to play

Test your understanding...



Q. 1) Given dict = {'li, 'sop', 'tree', 'ding', 'g'} and word = 'sopptreeg'. Is it possible to segment the given string into space separated segments of the given dict. words ?

Ans. 'sop' , 'p', 'tree', 'g'

'so', 'pp', 'tree', 'g'

It looks like the given word can't be separated.

Before you leave...

Knowledge of data structure and algorithms is must to simulate the real world problem in code.

If you want to learn more about this article, drop a comment below and reach out to us to let us know your interest.

If you enjoyed learning the fundamentals of DSA share your knowledge to your fellow programmers and social circle. May be someone out really needs this resource, and you might be helping them out by sharing it.

eeeeellldldkonoioid


How to calculate Compound Interest in Java? Compound Interest Calculator in Java Example Tutorial

Hello guys, if you are wondering how to calculate compound interest in Java or looking for Java program to calculate compound interest then you have come at the right place. Earlier I have shared how to calculate simple interest in Java and today I am going to share how to calculate compound interest in Java program. Calculating simple interest or compound interest are common coding problem which are taught in schools and colleges to teach you coding. The best thing about these coding exercise in Java are that everybody are familiar with them so you know the concept already and all you need to do is convert that solution into code which is the skill needed to become a coder or programmer. 

How to check if a Number is Power of Two in Java? [Bitwise AND Example]

Hello guys, if you are thinking about how to check if a given number is a power of two without using an arithmetic operator like division then you have come to the right place. In Java, you can use bitwise operators like bitwise AND check if a given number if the power of two or if the given number is even or odd. In this Java Programming tutorial, you will learn how to check if the number is the Power of two using a bitwise operator. The main purpose of this program is to teach you how to use bit-wise operators like bitwise AND (&)  in Java. A number is said to be the power of two if all its prime factors are 2, but in the binary world, things work a little differently. 

[Solved] How to count Vowels and Consonants in Java String Word? Example

Hello guys, if you are wondering how to count number of vowels and consonants in a given word in Java then you have come to the right place. In the past, I have shared 100+ data structure questions and more than 75 programming interview questions, and In this article, we will take on a popular programming exercise of counting vowels in a word. You need to write a Java program to count how many vowels in a String, which is entered from the command prompt. It's similar to the program of counting the occurrence of characters in a String, in fact, it's a special case, where you need to count occurrences of all vowels, which includes five characters a, e, i, o and u

[Solved] How to convert Hexadecimal to Decimal, Binary and Octal in Java? Example

Hexadecimal to decimal and binary conversion in Java
Hello guys, if you are wondering how to convert a Hexadecimal number to decimal and binary number in Java then you have come to the right place. Earlier, I have shown you how to convert decimal to binary in Java and in this Java program will convert Hexadecimal number to decimal, binary and Octal in Java programming language using JDK standard API methods. For beginners who are not familiar with number system, hexadecimal system is base 16 number, while decimal is base 10, Octal is base 8, and binary is base 2 numbers in Number systems. 

How to create a Function to add two numbers in Java? Variable Argument Example Tutorial

How to add two numbers in Java
Hello guys, if you are just starting with Java programming and wondering how to write a function to add two numbers in Java then you have come to the right place. In this Java program tutorial, we will add two numbers provided by the user on the command line. Write a Java program to add two numbers in Java is a common programming exercise for programmers and mostly asked in college exams, school homework, and Java courses as well. 

[Solved] How to solve climbing stairs problem in Java? Example

In this article, we are going to be solving the stairs problem using java, After that, I shall be explaining the concept of Array. but before we start writing codes it is fine to have an understanding of the problem we are about to solve. Given the number of stairs and the number of times you can move your legs, we would see how many possible ways you can achieve the climbing of stairs. The image below shows different possible ways you can climb stairs. For instance, let us say we have 5 steps on the stairs. and you can either walk with 2 moves or 1. 

How to Search an Element in Java Array with Example? ArrayUtils Tutorial

find an index of the object in Array
While programming in Java, many times we need to check if a String array contains a particular String or an integer array contains a number or not. Though array is an object in Java but it does not provide any convenient method to perform searching elements or finding elements. Sometimes you even need an index of an item stored in Array, unfortunately, Java API does not provide any direct method. Thanks to Open Source Apache Commons provides a utility class called ArrayUtils which allows you to check for an Item in Array, find its index in the array, find its lastIndex in Array and perform several other common operations. 

[Solved] How to solve a coin change problem in Java? Example

The coin change problem is one of the popular coding interview question and knowing how to solve this problem can help you during coding interview. It's also useful to learn a couple of tricks and data structure. This problem somewhat has to do with arrays, so we shall be discussing what an array is, But before we dive into this. we need to understand the problem. We are about to solve a coin problem by determining how many possible ways an amount can be paid. Suppose, Mary is a Businesswoman who deals with coin change. 

How to print a Right Triangle Pattern in Java - Example Tutorial

Hello Java Programmers, here we are back again with a pattern based exercise. In the past, I have shared article on how to print pyramid pattern of stars in JavaLeft Triangle Star Pattern, and Pyramid pattern of alphabets, and in this article, I will show you how to print a right triangle start pattern in Java.  Pattern based exercises are great way to learn programming and coding as it encourage you to use logic and use essential programming constructs like loop and arrays. 

[Solved] How to convert Decimal to Binary Number in Java? Example Tutorial

Hello guys, how are you doing? I have been sharing a lot of programming interview questions and coding problems for practice in this blog. Earlier, I have shared 21 String programing questions, 100+ data structure questions, and 20 System design questions and this week's programming exercise is to write a program to convert a decimal number to binary in Java. It's a simple exercise for beginners who have just started learning the Java programming language. Decimal numbers are base 10 numbers, which means there are exactly 10 digits to represent a number, starting from 0 to 9, on the other hand, the binary number system has just two digits 0 and 1, which is known as bits. 

[Solved] How to find all pairs which add up to a given value in an Integer Array in Java? Example

Hello guys, if you are preparing for programming job interview then you know that the problem of finding all pairs which adds up to a given value in a give array is a popular array based coding question. This question is also known as Two sum problem because you need to find pair of two elements in the array whose sum is equal to given number. For example, you have given an array of integers with values {1, 2, 3, 4, 5, 6} and you need to find all the pairs whose sum is equal to 5. In this case, there are two such pairs (1, 4) and (2, 3) so your program needs to print them into console. 

2 Ways to solve FizzBuzz in Java? [Example]

Hello guys, if you are learning to code or preparing for interviews and looking how to solve the FizzBuzz problem in Java then you have come to the right place. Earlier, I have shared 75 programming exercises and in this article, I will teach you how to solve the FizzBuzz problem in Java. FizzBuzz is one of the most frequently asked questions on programming interviews and used to filter candidates on Coding interviews who can't code. It looks extremely simple but it's tricky for those programmers or coders who struggle to structure their code or lack the ability to convert a simple algorithm into code. 

How to Find Highest Repeating Word from a File in Java [Word Count Solution]

Hello guys, if you are looking for a Java program to print the word and their count from a given file then you have come to the right place. Earlier, I have shared 100+ Data Strucutre and Algorithms Problems from interviews and in this article, I will show you how to find worlds and their count from a given file in Java. How to find the word and their count from a text file is another frequently asked coding question from Java interviews. The logic to solve this problem is similar to what we have seen in how to find duplicate words in a String, where we iterate through string and store word and their count on a hash table and increment them whenever we encounter the same word. 

How to Check if Given Number is Prime in Java - With Example

Hello guys, today, we are going to discuss one of the most common programming exercises for beginners is, write a program to check if a given number is prime or not? There are many ways to check if a number is prime or not, but the most common of them is the trial division, which is what we will see in this tutorial. In my opinion, these kinds of programs are their first steps towards algorithmic understanding. You first come up with a solution, which is driven by the fact that prime numbers are natural numbers, that are not divisible by any positive number other than 1 and themselves. Then, you write a for loop to check every number, starting from 1 to a given number, to see if the given number is divisible by any positive number or not. This leads you to the solution.

[Solved] How to Find 2 Largest Number from Integer Array in Java with Example

Hello guys, I have been sharing a lot of Programming interview questions and coding problems to learn programming better which is appreciated by you guys. In this post, I have come with other simple programming problems for Java beginners. I love to share short programming problems because they help in developing programming sense. Many people will argue against simple problems like prime numbers, palindrome, and factorial, but I really find them useful, especially for beginners. A beginner is far away to solve a complex data structure problem or even more complex problems like those that appear in TopCoder or other programming sites. Programmers learn gradually and they need the joy of doing something and seeing results much quicker than any other. Small success motivates them.

[Solved] How to Check If a Given String has No Duplicate Characters in Java? Unique Example

Hello guys, if you are looking to solve the classic problem "checking if a String has all Unique characters" or not then you have come to the right place. Earlier, I have shown you how to reverse String in place, and in this article, I will show you how to check for unique and duplicate characters in String.  You need to write a program to determine if a given string has all unique characters or not. For example input= "Java" then your function should return false because all characters are not unique, and if the input is "Python" then your program should return true because all characters in Python are unique.