Sorting array of strings (or words) using Trie
Last Updated :
02 Mar, 2023
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print them only once.
Examples:
Input : "abc", "xy", "bcd"
Output : abc bcd xy
Input : "geeks", "for", "geeks", "a", "portal",
"to", "learn", "can", "be", "computer",
"science", "zoom", "yup", "fire", "in", "data"
Output : a be can computer data fire for geeks
in learn portal science to yup zoom
Trie is an efficient data structure used for storing data like strings. To print the string in alphabetical order we have to first insert in the trie and then perform preorder traversal to print in alphabetical order.
Implementation:
CPP
// C++ program to sort an array of strings
// using Trie
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
struct Trie {
// index is set when node is a leaf
// node, otherwise -1;
int index;
Trie* child[MAX_CHAR];
/*to make new trie*/
Trie()
{
for (int i = 0; i < MAX_CHAR; i++)
child[i] = NULL;
index = -1;
}
};
/* function to insert in trie */
void insert(Trie* root, string str, int index)
{
Trie* node = root;
for (int i = 0; i < str.size(); i++) {
/* taking ascii value to find index of
child node */
char ind = str[i] - 'a';
/* making new path if not already */
if (!node->child[ind])
node->child[ind] = new Trie();
// go to next node
node = node->child[ind];
}
// Mark leaf (end of word) and store
// index of word in arr[]
node->index = index;
}
/* function for preorder traversal */
bool preorder(Trie* node, string arr[])
{
if (node == NULL)
return false;
for (int i = 0; i < MAX_CHAR; i++) {
if (node->child[i] != NULL) {
/* if leaf node then print key*/
if (node->child[i]->index != -1)
cout << arr[node->child[i]->index] << endl;
preorder(node->child[i], arr);
}
}
}
void printSorted(string arr[], int n)
{
Trie* root = new Trie();
// insert all keys of dictionary into trie
for (int i = 0; i < n; i++)
insert(root, arr[i], i);
// print keys in lexicographic order
preorder(root, arr);
}
// Driver code
int main()
{
string arr[] = { "abc", "xy", "bcd" };
int n = sizeof(arr) / sizeof(arr[0]);
printSorted(arr, n);
return 0;
}
Java
// Java program to sort an array of strings using Trie
// Author : Rohit Jain
// GFG user_id : @rj03012002
import java.util.*;
public class GFG {
// Alphabet size
static final int MAX_CHAR = 26;
// trie node
static class Trie {
// index is set when node is a leaf
// node, otherwise -1;
int index;
Trie child[] = new Trie[MAX_CHAR];
/*to make new trie*/
Trie()
{
for (int i = 0; i < MAX_CHAR; i++)
child[i] = null;
index = -1;
}
}
/* function to insert in trie */
static void insert(Trie root, String str, int index)
{
Trie node = root;
for (int i = 0; i < str.length(); i++) {
/* taking ascii value to find index of
child node */
int ind = str.charAt(i) - 'a';
/* making new path if not already */
if (node.child[ind] == null)
node.child[ind] = new Trie();
// go to next node
node = node.child[ind];
}
// Mark leaf (end of word) and store
// index of word in arr[]
node.index = index;
}
/* function for preorder traversal */
static boolean preorder(Trie node, String arr[])
{
if (node == null) {
return false;
}
for (int i = 0; i < MAX_CHAR; i++) {
if (node.child[i] != null) {
/* if leaf node then print key*/
if (node.child[i].index != -1) {
System.out.print(
arr[node.child[i].index] + " ");
}
preorder(node.child[i], arr);
}
}
return false;
}
static void printSorted(String arr[], int n)
{
Trie root = new Trie();
// insert all keys of dictionary into trie
for (int i = 0; i < n; ++i) {
insert(root, arr[i], i);
}
// print keys in lexicographic order
preorder(root, arr);
}
public static void main(String[] args)
{
String arr[] = { "abc", "xy", "bcd" };
int n = arr.length;
printSorted(arr, n);
}
}
Python3
# Python3 program to sort an array of strings
# using Trie
MAX_CHAR = 26
class Trie:
# index is set when node is a leaf
# node, otherwise -1;
# to make new trie
def __init__(self):
self.child = [None for i in range(MAX_CHAR)]
self.index = -1
# def to insert in trie
def insert(root,str,index):
node = root
for i in range(len(str)):
# taking ascii value to find index of
# child node
ind = ord(str[i]) - ord('a')
# making new path if not already
if (node.child[ind] == None):
node.child[ind] = Trie()
# go to next node
node = node.child[ind]
# Mark leaf (end of word) and store
# index of word in arr[]
node.index = index
# function for preorder traversal
def preorder(node, arr):
if (node == None):
return False
for i in range(MAX_CHAR):
if (node.child[i] != None):
# if leaf node then print key
if (node.child[i].index != -1):
print(arr[node.child[i].index])
preorder(node.child[i], arr)
def printSorted(arr,n):
root = Trie()
# insert all keys of dictionary into trie
for i in range(n):
insert(root, arr[i], i)
# print keys in lexicographic order
preorder(root, arr)
# Driver code
arr = [ "abc", "xy", "bcd" ]
n = len(arr)
printSorted(arr, n)
# This code is contributed by shinjanpatra
C#
// C# program to sort an array of strings using Trie
using System;
class GFG
{
static int MAX_CHAR = 26;
// trie node
public class Trie
{
// index is set when node is a leaf node, otherwise -1
public int index;
public Trie[] child = new Trie[MAX_CHAR];
// constructor to make a new trie node
public Trie()
{
for (int i = 0; i < MAX_CHAR; i++)
child[i] = null;
index = -1;
}
}
/* function to insert in trie */
static void Insert(Trie root, string str, int index)
{
Trie node = root;
for (int i = 0; i < str.Length; i++)
{
/* taking ASCII value to find the index of the child node */
int ind = str[i] - 'a';
/* making a new path if not already */
if (node.child[ind] == null)
node.child[ind] = new Trie();
// go to the next node
node = node.child[ind];
}
// mark the leaf node (end of the word) and store the index of the word in arr[]
node.index = index;
}
/* function for preorder traversal */
static void Preorder(Trie node, string[] arr)
{
if (node == null)
{
return;
}
for (int i = 0; i < MAX_CHAR; i++)
{
if (node.child[i] != null)
{
/* if leaf node, then print the key */
if (node.child[i].index != -1)
{
Console.WriteLine(arr[node.child[i].index] + " ");
}
Preorder(node.child[i], arr);
}
}
}
static void PrintSorted(string[] arr, int n)
{
Trie root = new Trie();
// insert all keys of the dictionary into the trie
for (int i = 0; i < n; i++)
{
Insert(root, arr[i], i);
}
// print the keys in lexicographic order
Preorder(root, arr);
}
static void Main(string[] args)
{
string[] arr = { "abc", "xy", "bcd" };
int n = arr.Length;
PrintSorted(arr, n);
}
}
// This code is contributed by Aman Kumar.
JavaScript
<script>
// JavaScript program to sort an array of strings
// using Trie
const MAX_CHAR = 26;
class Trie {
// index is set when node is a leaf
// node, otherwise -1;
/*to make new trie*/
constructor()
{
this.child = new Array(MAX_CHAR).fill(null);
this.index = -1;
}
}
/* function to insert in trie */
function insert(root,str,index)
{
let node = root;
for (let i = 0; i < str.length; i++) {
/* taking ascii value to find index of
child node */
let ind = str.charCodeAt(i) - 'a'.charCodeAt(0);
/* making new path if not already */
if (node.child[ind] == null)
node.child[ind] = new Trie();
// go to next node
node = node.child[ind];
}
// Mark leaf (end of word) and store
// index of word in arr[]
node.index = index;
}
/* function for preorder traversal */
function preorder(node, arr)
{
if (node == null)
return false;
for (let i = 0; i < MAX_CHAR; i++) {
if (node.child[i] != null) {
/* if leaf node then print key*/
if (node.child[i].index != -1)
document.write(arr[node.child[i].index],"</br>");
preorder(node.child[i], arr);
}
}
}
function printSorted(arr,n)
{
let root = new Trie();
// insert all keys of dictionary into trie
for (let i = 0; i < n; i++)
insert(root, arr[i], i);
// print keys in lexicographic order
preorder(root, arr);
}
// Driver code
let arr = [ "abc", "xy", "bcd" ];
let n = arr.length;
printSorted(arr, n);
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(n*m) where n is the length of the array and m is the length of the longest word.
Auxiliary Space: O(n*m)
Similar Reads
Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates) Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: Input : arr[] = { "abc", "xyz", "abcd", "bcd", "abc" } Output : abc abc abcd bcd xyz Input : arr[] = { "geeks", "for", "geeks", "a", "porta
9 min read
Sort given words as Array of Strings Given an array of strings Arr[]. The task is to sort them in lexicographic order. Examples: Input: Arr[] = {"sort", "this", "list"}Output: [list, sort, this] Input: Arr[] = {"sun", "earth", "mars", "mercury"}Output: [earth, mars, mercury, sun] Selection Sort Approach: The same problem can also be so
15+ min read
Count of given Strings in 2D character Array using Trie Counting the number of occurrences of a given string in a 2D character array using a Trie. Examples: Input: vector<string> grid = {"abcde", "fghij", "xyabc", "klmno",}; string word = "abc";Output: 2Explanation: abc occurs twice in "abcde", "xyabc" Input: vector<string> grid = {"abcde", "
11 min read
Print Strings In Reverse Dictionary Order Using Trie Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit. Given an array of strings. The task is to print all strings in reverse dictionary order using Trie. If there are duplicates in the input array, we need to print them only on
12 min read
Print Strings In Reverse Dictionary Order Using Trie Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit. Given an array of strings. The task is to print all strings in reverse dictionary order using Trie. If there are duplicates in the input array, we need to print them only on
12 min read
Pattern Searching using a Trie of all Suffixes Problem Statement: Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.As discussed in the previous post, we discussed that there are two ways efficiently solve the above probl
13 min read