Type Here to Get Search Results !

# Lexicographically Ordering of Strings in Java

0

Lexicographically Ordering of Strings

You will be given N number of strings. You have to find the lexicographically smallest string and the lexicographically largest string among these strings.

Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. The first line of each test case consists of N. In the next line are N space separated strings of lower case Latin letters only.

Output:

Corresponding to each test case, in a new line, print the lexicographically smallest string and the lexicographically largest string among the given strings separated by a single space between them.

Constraints:

1 ≤ T ≤ 100

1 ≤ N ≤ 100

1 ≤ Length of each string ≤ 40

Example:

Input

3
3
a ab abc
3
a a b
3
z xy t

Output

a abc
a b
t z

Solution Explanation

We are using Java String compareTo() method to solve this problem.

The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0.

It compares strings on the basis of Unicode value of each character in the strings.

If first string is lexicographically greater than second string, it returns positive number (difference of character value). If first string is less than second string lexicographically, it returns negative number and if first string is lexicographically equal to second string, it returns 0.

```if s1 > s2, it returns positive number

if s1 < s2, it returns negative number

if s1 == s2, it returns 0  ```

Code

```import java.util.*;
import java.lang.*;
import java.io.*;

class CodingHumans {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
String arr[]=new String[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.next();
}
String currstr=arr;
String Lmin=currstr;
String Lmax=currstr;
for(int  i=0;i<n;i++)
{
if(Lmax.compareTo(arr[i])<0)
{
Lmax=arr[i];
}
if(Lmin.compareTo(arr[i])>0)
{
Lmin=arr[i];
}
}
System.out.println(Lmin+" "+Lmax);
}
}
}
```

Input

```3
3
a ab abc
3
a a b
3
z xy t```

output

```a abc
a b
t z```