×

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

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.