create a Trie from an array of strings using in swift
The concept is : you have given an array of strings like :
# The input will be always in the below format "x1>x2>x3...>xn=Integer" else it is invalid input #
private let input = [
"a>b>c=1",
"a>b>c=2",
"d>c=3",
"f>e=10",
"a>b=20", // Invalid, Node(b) has Child, cannot insert the value
"a>b>c>d=11", // Invalid , Node(c) has value, but trying to insert child, invalid case
"a>a>a=100"
]
(1). Let's consider the first input : "a>b>c=1" which consists of 2 parts based on "=" operator "a>b>c" and "1".
The first part is used for tree hierarchy where x>y means x is parent of y and the value "1" will be child of last node. It creates a tree like below for the first time as tree is empty at beginning.
( Root ) --> ("a") --> ("b") --> ("c") --> [1]
(2) Consider 2nd input : "a>b>c=2". Divide the input into 2 parts "a>b>c" and "2" based on "=". While processing "a>b>c", it's simply traversing because node("a"), node("b"), node("c") are in correct hierarchy and update the value node by appending value=2 so value([1,2]). Tree looks like :
( Root ) --> ("a") --> ("b") --> ("c") --> [1,2]
(3) Considering "d>c=3", the tree looks like :
( Root ) --> ("a") --> ("b") --> ("c") --> [1,2]
|
--> ("d") --> ("c") --> [3]
(4) Considering "a>b=20" input produce an ERROR because node("b") has a child node("c") so you cannot insert value([20]) for node("b"), So, don't process for this input. (no modification in tree)
(5) considering "a>b>c>d=11" input, produce an ERROR because node("c") has a Value([1,2]) child, you cannot add a node("d") as child of node("c"), So, don't process for this input. (no modification in tree)
You have to construct the Trie like below considering the above input.
{
"a" : { "b" : { "c" : [1,2] },
"a" : { "a" : [100] }
},
"d" : { "c" : [3] },
"f" : { "e" : [10] }
}