×

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages.

Example:

Words = { "aac", "abc", "aaa" }

Output

c, a, b

Algorithm:

(1) Compare two words that are next to each other at once, such as word1 with word2, word2 with word3,..., and word(startIndex) with the word(startIndex + 1).

(2) Next, we compare each character for the two words in question.

(2a) If the two characters are distinct, we stop comparing them at this point and determine that the character from word(startIndex) appears first.

(2b) If both elements are identical, we compare until one of the words is completed or until (2a) happens.

(3) This comparison process is repeated until all words have been evaluated.

Once a character set has been identified in (2a), we give it to the class "AlienCharacters," which is in charge of character ordering overall. The goal is to keep the elements in a sorted array in the proper sequence (DNode). A map (C# Dictionary) is utilized as an indexing object to reduce complexity to O and improve the insertion time into the linked list (1). This enhancement is compared to the prior approach, which employed topology sort.

Bounding circumstances:

1. The start index needs to be in the range.

2. If we exhaust one term when comparing two words, the size of the two words will vary. Only compare once an opponent has run out of fuel.

Filename:AlienLanguage.java

//Java Program for printing the order of characters in the alien language
import java. util.*;
// The class for graphs
class Graphs {


	// The array contains the list of all nodes in the adjective points
	private final LinkedList<Integer>[] adjacencyLists;
	Graphs(int nuVertices)
	{
		adjacencyLists = new LinkedList[nuVertices];
		for (int vertexIndexs = 0; vertexIndexs < nuVertices;
			vertexIndexs++) {
			adjacencyLists[vertexIndexs] = new LinkedList<>();
		}
	}
	// the method used for adding the edge of the graph to the vertex
	void addEdges(int startVertexs, int endVertexs)
	{
		adjacencyLists[startVertexs].add(endVertexs);
	}
	private int getNoOfVertices()
	{
		return adjacencyLists.length;
	}
	// the recursive call for sorting
	private void topologicalSortUtils(int currentVertexs, boolean[] visiteds, Stack<Integer> stacks)
	{
		// the current node is in the state of marked
		visiteds[currentVertexs] = true;
		// the function calls for all of the adjacent vertices in the graph
		for (int adjacentVertexs :
			adjacencyLists[currentVertexs]) {
			if (!visiteds[adjacentVertexs]) {
				topologicalSortUtils(adjacentVertexs, visiteds, stacks);
			}
		}
		// the current vertex is moved to the stack
		stacks.push(currentVertexs);
	}
	// the sort function of the vertices
	void topologicalSorts()
	{
		Stack<Integer> stacks = new Stack<>();
		// the remaining are then are marked
		boolean[] visiteds = new boolean[getNoOfVertices()];
		for (int i = 0; i < getNoOfVertices(); i++) {
			visiteds[i] = false;
		}
		// To save a Topological Sort beginning with all vertices
		//each one by one, call the recursion equipment and parts.
		for (int i = 0; i < getNoOfVertices(); i++) {
			if (!visiteds[i]) {
				topologicalSortUtils(i, visiteds, stacks);
			}
		}
		// display the elements of the stack
		while (!stacks.isEmpty()) {
			System.out.print((char)('a' + stacks.pop()) + " ");
		}
	}
}
public class AlienLanguage{
	// This function determines and displays the character 
	//order from a sorted array of words. 
	//The number of alphabet letters, starting with "a," 
	//is known as "alphas." For the sake of simplicity, 
	//just the first 'alpha' elements in the phrases array are allowed 
	//in this function. For instance, 
	//words should only contain letters 
	//'a', 'b', 'c', 'd', 'e', 'f', and 'g' if the alphas are 7.
	private static void printOrder(String[] words, int num, int alphas)
	{
		//the graph is created
		Graphs graphs = new Graphs(alphas);
		for (int i = 0; i < num - 1; i++) {
			// the initial 2 words are compared
			String words1 = words[i];
			String words2 = words[i + 1];
			for (int j = 0; j < Math.min(words1.length(), words2.length()); j++) {
				// if the character mismatches, it is added to the graph
				if (words1.charAt(j) != words2.charAt(j)) {
					graphs.addEdges(words1.charAt(j) - 'a',words2.charAt(j) - 'a');
					break;
				}
			}
		}
		// the sorted graph values are displayed
		graphs.topologicalSorts();
	}
	public static void main(String[] args)
	{
		String[] words = { "abc", "aac", "aba" };
		printOrder(words, 3, 3);
	}
}

Output

c a b

Analysis of Complexity:

For ease of comprehension, the following C# code includes method-wise time complexities.

If "N" is the total amount of words in the given alien language and "L" is the maximum word size, and "C" is the total amount of distinct characters.

Time Complexity: O(N*L)

Space Complexity: O(C)


Related Topics

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.