Top 15 Courses to Learn System Design and Software Architecture in 2025 - Best of Lot

Software design or System design is one of the tricky concepts to master. You can quickly learn a programming language like Java or Python, but creating software using that programming language is a totally different thing. That's where software design and coding skills come to the rescue. It's actually an art to structure your program, design your modules, specify boundaries and interactions with other parts of the system so that they are easier to read, maintain, and flexible to change. It's one of the most essential skills for a software developer but often gets ignored. If you look for an online course to learn Software design and architecture, you won't find many, forget about good ones.

Review - Is AlgoMonster Good Resource For Coding Interview Preparation in 2025?

Hello guys, if you are preparing for coding interviews and wondering whether joining AlgoMonster is right decision or not then you have come to the right place. Earlier I have shared best website for coding interview preparation, books, and best coding interview courses and in this article, we will review Algo Monster, one of the top site for coding interview preparation. Before we review Algomonster, let me tell you what it really is. For those of you who don't know, Algomonster is a legit site and basically an interview prep site with a focus on coding that will help you clear your interview and land your dream coding job. 

Top 8 Online Courses to Learn System Design and Software Architecture on Udemy (2025)

Hello friends, If you're aiming to master Software Architecture and System Design in 2025, you're in the right place. Whether you're preparing for tough technical interviews or simply want to become a better software engineer, understanding system design is a must. But let’s be honest—it’s also one of the most challenging topics to master. Many developers, including experienced ones, struggle with system design interviews—especially when applying to top tech companies like Google, Meta, Amazon, Apple, Microsoft, and Netflix (formerly known as FAANG, now MAANG).

70+ Coding Interview Questions for Software Engineers and Developers in 2025

There are a lot of computer science graduates and programmers applying for programming, coding, and software development roles at startups like Uber and Netflix and big organizations like Amazon, Microsoft, and Google.  They are also quite popular on service-based companies like Infosys, TCS, or Luxsoft, but many of them have no idea of what kind of programming interview questions to expect when you’re applying for a job with these companies. Things have also changed a lot in the last few years and coding interviews have become tougher. Now you need to go through a couple of coding interview rounds but you also need to prepare for System design problems which wasn’t normal in the last decade.

Difference between Daemon Thread vs User Thread in Java? Example

A thread is used to perform parallel execution in Java e.g. while rendering screen your program is also downloading the data from the internet in the background. There are two types of threads in Java, user thread and daemon thread, both of which can use to implement parallel processing in Java depending upon the priority and importance of the task. The main difference between a user thread and a daemon thread is that your Java program will not finish execution until one of the user threads is live. JVM will wait for all active user threads to finish their execution before it shutdown itself. 

How to join two threads in Java? Thread.join() example

You can join two threads in Java by using the join() method from java.lang.Thread class. Why do you join threads? because you want one thread to wait for another before starts processing. It's like a relay race where the second runner waits until the first runner comes and hands over the flag to him. Remember, unlike sleep(), join() is not a static method so you need an object of java.lang.Thread class to call this method. Now, who calls and who wants, and which thread dies? for example, if you have two threads in your program main thread and the T1 which you have created. 

How to stop a thread in Java? Example

Today we're going to learn about how to stop a thread in Java. It's easy to start a thread in Java because you have a start() method but it's difficult to stop the thread because there is no working stop() method. Well, there was a stop() method in Thread class, when Java was first released but that was deprecated later. In today's Java version, You can stop a thread by using a boolean volatile variable.  If you remember, threads in Java start execution from the run() method and stop, when it comes out of the run() method, either normally or due to any exception. You can leverage this property to stop the thread. 

10 Things about Threads Every Java Programmer Should Know

Thread in Java is one of those topics which always confuse beginners but given the importance and strength it provides to the Java language, it's very important for every Java developer to learn and understand the fundamental concept of multi-threading and basic points about Thread in Java. I had started thread programming in Java by animating a couple of words in Applets, that was an amazing experience to code animation, but after spending almost 10 years on developing core Java applications and I am still discovering things about threading and concurrency. My first program which involves Thread had three words dropping from each corner of the screen and I was excited to see that animation driven by Java thread.

Difference between int and Integer Types in Java? Example

Both int and Integer are two important data types in Java that often cause confusion between new Java developers. Both int and Integer are used to represent numeric data and related to each other in the sense of primitive and Object. Int is a primitive data type that has 32-bit and stores values from  -2^31 to 2^31-1 while Integer is a class that wraps an int primitive inside it. In this article, you will learn why we need Integer Class in Java, particularly, if we already had the int data type, how to convert from int to Integer in Java, and various points on Integer in Java, ranging from basics to advanced BigInteger and AtomicInteger stuff.

What is Thread and Runnable in Java? Example

What is Thread in Java?
Thread in Java is an independent path of execution that is used to run two tasks in parallel. When two threads run in parallel that is called multithreading in Java. Java is multithreaded from the start and has excellent support of Thread at language level e.g. java.lang.Thread class, synchronized keyword, volatile and final keyword make writing concurrent programs easier in Java than any other programming language like C++. Being multi-threaded is also a reason for Java's popularity and being the number one programming language. 

What is blank final variable in Java - Example

What is a blank final variable in Java?
The blank final variable in Java is a final variable that is not initialized while declaration, instead they are initialized in a constructor. Java compiler will complain if a blank final variable is not initialized during construction. If you have more than one constructor or overloaded constructor in your class then a blank final variable must be initialized in all of them, failing to do so is a compile-time error in Java. Alternatively, you can use constructor chaining to call one constructor from another using this keyword, in order to delegate initialization of a blank final variable in Java. In this Java tutorial, we will see what is blank final variable is in Java and a code example on How to use a blank final variable.

Access Modifiers in Java - Public, Private, Protected, and Package Examples

public, private, protected and package or default are four access modifiers available in Java. These access modifiers provide Java programmers to control the accessibility or visibility of a class, method, or any field of a class. A good understanding of public, private, or protected modifiers is required in order to implement proper encapsulation in Java and create a Java program that is easier to maintain. In this Java tutorial, we will see what is public, private, protected and default modifiers are, which modifiers can be used with top-level class and nested class, and what is the difference between public, private, protected, and default modifiers in Java.

How to display date in multiple timezone in Java with Example - PST GMT

We can use SimpleDateFormat class to display a date in multiple Timezone in Java. While working in a global Java application it's quite common to display dates in the different time zone, classical example is Server is running on either PST or GMT timezone and clients are global or at least running on global trading hubs like Hong-kong, Mumbai, Tokyo, London, etc. Unfortunately, the Date and Time API in Java is quite tricky and until you have a good understanding of Date and Time classes and methods like Calendar, SimpleDateFormat, and thread-safety issues, You can easily create bugs. 

JDBC - How to Convert java.sql.Date to java.util.Date in Java with Example

How to convert java.sql.Date into a java.util.Date and vice-versa is a popular JDBC interview question which is also asked a follow-up question of the difference between java.sql.Date and java.util.The date which we have seen in our last article. Since both SQL date and Util date store values as a long millisecond, converting them back and forth is easy. Both java.sql.Date and java.util.The date provides a convenient method called getTime() which returns a long millisecond equivalent of a wrapped date value. Here is a quick example of converting java.util.Date to java.sql.Date and then back to util Date. 

5 Essential JDK 7 Features for Java Programmers

What is new in Java or JDK 7
It's close to a year now JDK 7 or Java 7 has been released, still, programmer asks what is new in Java 7 ? What is the best feature introduced in JDK7, where is the list of all Java 7 new features, etc? I thought to let's document Top 5 new features introduced in Java 7 for easy reference, this will not only answer What is new in Java 7 but also provide a quick overview of What are those features in Java 7.  Java 7 introduced many new features in Java programming language like try-catch with a resource, String in Switch, etc but it also makes a lot of changes on Java Development API by introducing a new File API in Java and several other minor changes. Like you can now find hidden files from the Java programs without applying any hack. anyway let's see my list of Top 5 Java 7 features :

Difference between DOM vs SAX Parser in Java - XML Parsing in Java

DOM vs SAX parser in Java
DOM and SAX parser are the two most popular parsers used in the Java programming language to parse XML documents. DOM and SAX concept is originally XML concept and Java programming language just provide an API to implement these parsers. Despite both DOM and SAX are used in XML parsing, they are completely different from each other. In fact difference between DOM and SAX parser is a popular Java interview question asked during Java and XML interviews. DOM and SAX parser has a different way of working, which makes Java programmer understand the difference between DOM and SAX parser even more important.

How to configure Daily Log File Rolling in Java using Log4j - DailyRollingFileAppender Example

Hello guys, today, I am going to share one small but the useful tip about logging in to your Java application. If your Java application is a weekly restart, I mean it starts on Sunday and not again on the weekday, then you really want to have separate log files for each day. This helps during troubleshooting and debugging. But If you are facing a problem where your log files are not rolling daily and becoming bigger and bigger after each passing day, making it challenging to search anything in case of any production issue, then it might be that you have not configured your Log4j properly to roll your logs daily.

Eclipse and NetBeans Keyboard Shortcuts for Java Programmers - Example

If you are a Java developer who has been using Eclipse for Java development, but you need to use Netbeans for your current project for various reasons, this article is for you. Whenever we transition between tools, we need the equivalent of one into other. For example, if you are an Eclipse power user who is used to Ctrl + Shift + R and Ctrl + Shift + T, you miss those as soon as you start using Netbeans shortcuts. One thing to keep your productivity up is to quickly find the equivalent shortcut in a new tool, like, Netbeans if you are switching from Eclipse or vice-versa.

How to convert int value to a Long object in Java? Examples

Suppose you have an int variable but the part of the application is expecting a Long object, how do you convert a primitive int to a Long object in Java? It shouldn't be a problem, right? after all long is a bigger data type than int, so all int values are acceptable as long, but we also need a Long object, not just the long primitive value. Now, the problem is reduced to converting a long primitive to a Long object, which is not really a problem if you are running on a JRE version higher than Java 5. But, sometimes autoboxing is not efficient like when you have to convert multiple long values into the Long object in a loop. 

How to Create Random Alphabetic or AlphaNumeric String of given length in Java? SecureRandom Example

Hello Java programmers, if you want to create a random alphanumeric string and looking for examples then you have come to the right place. Earlier, I have shown you how to generate random numbers in a range, and in this article, you'll learn how to generate random alphanumeric String in Java. Suppose, you want to generate an alphabetic or alphanumeric string of a given length in Java? How do you do it? Well, if you are like me, you probably search a library like Apache commons-lang or Google Guava for something which can do this task. It's a good thing. There is no point in re-inventing a wheel if a tried and tested solution already exists. In fact, Effective Java, the most respected book in the Java world also suggests knowing and use your library. 

How to Order and Sort Objects in Java? Comparator and Comparable Example

Java Object Sorting Example
How do you sort a list of Objects in Java is one of the frequently asked coding questions in Java interviews and surprisingly not every Java programmers know How sorting of object happens in Java. Comparator and Comparable interface along with Collections.sort() method are used to sort the list of objects in Java. compare() and compareTo() method of Comparator and Comparable interface provides comparison logic needed for sorting objects. compareTo() method is used to provide Object's natural order sorting and compare() method is used to sort Object with any arbitrary field. 

Difference between int and Integer data type in Java? Example

The first and foremost difference between an int and Integer or a char and Character is that the former is a primitive data type while the latter is a class, also known as wrapper class because they wrap the primitive data type inside it. When you first start learning Java, you start with primitive data types like int, long, char, byte, boolean, float, and double but slowly you learn about Object, and sometime later you know about Integer, Long, Character, Byte, Boolean, Float, and Double. At this point in time, you may wonder, what is the real difference between an int and Integer? isn't both the same? We can pass Integer where int is expected and vice-versa then why on the earth we have both int and Integer?

JDBC - How to get Row and Column Count From ResultSet in Java? Example

One of the common problems in JDBC is that there is no way to get the total number of records returned by an SQL query. When you execute a Statement, PreparedStatement, or CallableStatement using execute()or executeQuery() they return ResultSet and it doesn't have any method to return the total number of records it is holding. The only way to find the total number of records is to keep the count while you are iterating over ResultSet while fetching the result. This way, you can print the total number of rows returned the SQL query but only after you have processed all records and not before, which may not be the right way and incur significant performance cost if the query returns a large number of rows.

Can You Create Instance of Abstract class in Java? Answer

Hello Java Programmers, how are you doing? Hope you are doing well. It's been a long since  I shared a core Java interview question in this blog, so let's start with that. Earlier I have shared one of the frequently asked questions in Java, can we make an abstract class final in Java and my readers really liked it and asked for more such questions. So, today I am going to talk about whether you can create an instance of an Abstract class in Java or not? This is another interesting core Java question that you will find on telephonic interviews, a written test that has multiple-choice questions and most notably Oracle certified Java programmer certification like OCAJP 8  and OCAJP 11.

How to convert String to Enum in Java? ValueOf Example

valueOf Example in Java Enum
valueOf method of Java Enum is used to retrieve Enum constant declared in Enum Type by passing String in other words valueOf method is used to convert String to Enum constants. In this Java Enum valueOf example we will see how to use the valueOf method in Java. valueOf method is implicitly available to all Java Enum because every enum in Java implicitly extends java.lang.Enum class. valueOf method of enum accepts exactly the same String which is used to declare Enum constant to return that Enum constant. valueOf method is case-sensitive and invalid String will result in IllegalArgumentException.

The Ultimate Guide to Package in Java? Examples

If you are learning Java then you might have come across a package concept and if you are wondering what is package and why should we use it then you have come to the right place. In this article, I will explain what is package in Java and other stuff around the package, including some best practices which using the package in Java. In the simplest form, a package is a way to organize related functionality or code in a single place in Java. If you look from a File System perspective then a package in Java just represent a directory where Java source file is stored in compilation and class files are stored after compilation. 

How to read a file line by line in Java? BufferedReader Example

Hello Java Programmers, if you are looking for a way to read a file line by line in Java then don't worry, Java provides java.io  package in JDK API for reading File in Java from File system e.g. C:\ or D:\ drive in Windows or any other directory in UNIX. First, you can use FileInputStream to open a file for reading. FileInputStream takes a String parameter which is a path for the file you want to read. Be careful while specifying File path as path separator is different on Window and UNIX. Windows uses backslash while UNIX uses forward slash as a path separator. 

Java Enum with Constructor Example

Java Enum with Constructor
Many Java developers don't know that Java Enum can have a constructor to pass data while creating Enum constants. This feature allows you to associate related data together. One example of passing arguments to enum Constructor is our TrafficLight Enum where we pass the action to each Enum instance e.g. GREEN is associate with go, RED is associated with stop, and ORANGE is associated with the slow down

Could not create the Java virtual machine Invalid maximum heap size: -Xmx

"Could not create the Java virtual machine" is a general JavaVirtual Machine error when you run java command directly or indirectly and it's not able to create a virtual machine because of invalid maximum heap size, invalid minimum heap size, or just an error in command line. This error not only come when you run Java program from the command line but also when you run them using any IDE like Eclipse or Netbeans.

ArrayList vs Vector in Java? Interview Question Answer

ArrayList vs Vector in Java
ArrayList and Vector are the two most widely used Collection classes in Java and are used to store objects in an ordered fashion. Every Java programmer which is introduced to Java Collection Framework either started with Vector or ArrayList. For beginners Difference between Vector and ArrayList in Java and LinkedList vs ArrayList are the two most popular Java Interview questions. ArrayList vs Vector is not only important from an interview perspective but also on the effective use of Java Collection API. 

The Ultimate Guide of Enum in Java - Examples

Apart from the Class and Interface, Enumeration type or Enum is another popular type in Java programming language. Enum allows you to represent a fixed number of well-known things in a type-safe manner e.g. days of the week, days of the month, planets in the solar system, buttons on the remote control, keys on the keyboard, and suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to represent the fixed number of things, known as enum int pattern and enum string pattern as described in classic Effective Java by none other than Joshua Bloch. Though they served the purpose, they had some major drawbacks which resulted in poor quality code.

What is class file in Java? Example

What is the class file in Java?
Class file in Java is compiled from of Java source file. When we compile a Java program written in a Java source file ended with a .java extension, it produces one more class file depending upon how many classes are declared and defined in that Java source file. One Java source file can only contain one public class, and its name must match with the name of the file like HelloWorld.java file can contain a public class whose name should be HelloWorld as shown below :

Difference between static and non static nested class in Java? Example

Static vs. non Static class in Java
In Java, you can make a class either static or non-static. Now, what is the difference between making a class static vs. non-static? Well, there is a lot of difference between them. First of all, there are two kinds of classes in Java, one is called a top-level class, and the other is called a nested class. As the name suggested, a top-level class is a class that is declared in the .java file and not enclosed under any other class. On the other hand, a nested class is declared inside another class. The class which enclosed nested class is known as Outer class. 

How to read file in Java using Scanner Example - text files

Reading a file with Scanner
From Java 5 onwards java.util.Scanner class can be used to read file in Java. Earlier we have seen examples of reading file in Java using FileInputStream and reading file line by line using BufferedInputStream and in this Java tutorial, we will See How can we use Scanner to read files in Java. Scanner is a utility class in java.util package and provides several convenient methods to read int, long, String, double etc from a source which can be an InputStream, a file, or a String itself.

Difference between throw vs throws in Java? Answer

throw vs throws in Java
throw and throws are two Java keywords related to the Exception feature of the Java programming language. If you are writing a Java program and familiar with What is Exception in Java, it's a good chance that you are aware of What is throw and throws in Java. In this Java tutorial, we will compare throw vs throws and see some worth noting differences between throw and throws in Java. Exception handling is an important part of the Java programming language which enables you to write robust programs. There are five keywords related to Exception handling in Java like try, catch, finally, throw, and throws.

How to read User Input from Console in Java? Scanner Example

Apart from reading files, Scanner can also read user input from Console in Java. Just like in the case of reading files, we have provided File as a source for scanning, We need to provide System.in as a source to scan for user input in Console. Once you created and initialized java.util.Scanner, you can use its various read method to read input from users. If you want to read String, you can use nextLine(), if you want to read integer numbers, you can use nextInt(). 

How to Find IP address of localhost or a Server in Java? Example

In today's Java programming tutorial, we will learn some networking basics by exploring the java.net package. One of the simple Java network programming exercises, yet very useful, is to write a program to find the IP address of the local host in Java. Sometimes this question is also asked to find the IP address of the Server on which your Java program is running or find the IP address of your machine using Java etc. In short, they all refer to localhost. For those who are entirely new in the networking space, there are two things to identify a machine in a network, which could be LAN, WAN, or The Internet. 

15 People Java Developers Should Follow on Twitter

If you are passionate about Java and would like to follow Java bloggers into Twitter then here is my list of 15 people you can follow on Twitter to keep yourself up-to-date and engage in the Java world. These people regularly share the latest things in Java, JVM, Spring, Hibernate, and other Java technology. By following them, you will not only know about their latest work but also what's happening in the Java world. You might be thinking just 15 people, well, there are many more who is not on this list but I regularly share their Twitter handles via my Twitter account @javinpaul and @Javarevisited. If you are following me then you will automatically get to know about them.

Java Keyword Cheat Sheet - Meaning and Usage

Knowing keywords of a programming language is very important to understand its features, and Java has rich set of keyword, going along with rich set of functionalities. The first keyword, I learn while writing Java program was public, static and void, not surprisingly they are picked from main method. Our instructor explained meaning of each keyword, saying that its, always remember why main is public, static and void main Java. 

Video example - Dijkstra's Algorithm shortest path in Graph


Video example - Dijkstra's Algorithm shortest path in Graph

Dijkstra's Algorithm in Graph theory allows you to find least cost path or shortest path between two nodes in directed and weighted graph. Dijkstra's Algorithm is one of the important concept of Graph theory and often asked in Exams and interviews. Frankly speaking Its not easy to understand Dijkstra's Algorithm , at least until you have a good example and this leads me to search for simple and easy to learn example of Dijkstra's Algorithm which landed me on this video. I have earlier shared Graph traversal BFS and DFS algorithm from this same author and when I found his video on Dijkstra's Algorithm, I knew this is going to be another best. By the way Dijkstra's Algorithm has several practical usage like finding shortest path between cities for Air planes route or bus route as cities and driving path between cities fits nicely
as vertices of Graph and directed and weighted path between them. In Dijkstra's Algorithm , path between two nodes which are unreachable directly is assumed as infinity. I suggest watching this video example more than one time if you are unsure how Dijkstra's Algorithm works.


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