import
java.io.*;
import
java.util.*;
class
GFG {
public
static
class
Trie {
Trie []arr =
new
Trie[
27
];
int
idx;
};
public
static
Trie root;
public
static
void
insert(String word,
int
i)
{
Trie temp = root;
for
(
int
ch=
0
; ch < word.length(); ch++){
if
(temp.arr[word.charAt(ch) -
'a'
] ==
null
) {
Trie t =
new
Trie();
temp.arr[word.charAt(ch) -
'a'
] = t;
}
temp = temp.arr[word.charAt(ch) -
'a'
];
temp.idx = i;
}
}
public
static
int
search(String word)
{
Trie temp = root;
for
(
int
ch=
0
; ch < word.length(); ch++) {
if
(temp.arr[word.charAt(ch) -
'a'
] ==
null
)
return
-
1
;
temp = temp.arr[word.charAt(ch) -
'a'
];
}
return
temp.idx;
}
public
static
void
findMatchingString(
String[] words,
int
n,
String[][] Q)
{
String temp, t=
""
;
for
(
int
i =
0
; i < n; i++) {
temp =
"{"
+ words[i];
for
(
int
j = words[i].length() -
1
;
j >=
0
; j--) {
t = words[i].charAt(j) + temp;
temp = t;
insert(t, i);
}
}
for
(
int
i =
0
; i < Q.length ; i++) {
String prefix = Q[i][
0
];
String suffix = Q[i][
1
];
temp = suffix +
"{"
+ prefix;
int
res;
res = search(temp);
if
(res != -
1
) {
System.out.println(words[res]);
}
else
System.out.println(
"-1"
);
}
}
public
static
void
main (String[] args) {
String[] arr
= {
"apple"
,
"app"
,
"biscuit"
,
"mouse"
,
"orange"
,
"bat"
,
"microphone"
,
"mine"
};
int
N =
8
;
root=
new
Trie();
String[][] Q = { {
"a"
,
"e"
}, {
"mi"
,
"ne"
} };
findMatchingString(arr, N, Q);
}
}