Search code examples
javastringsortingcomparison

Sorting Strings and extracting common elements of two String arrays in Java


I was asked to write down a Java function sharedStr that by given 2 sorted arrays of Strings, returns the number of Strings that appear in both of the arrays.

The solution for this code must be linear, which means that I must go through each array only once. Otherwise, I could just compare each String in the first array to all the Strings in the other array.

For example the following call to sharedStr

sharedStr({"Call","me","Ishmael"},{"Call","me","Jonha"});

must return 2. I would like your help to understand what does it mean sorted arrays that contain Strings? There isn't any special description of the way the arrays have been sorted. What is the basic ordinary sorting of Strings?

How does one compare between two Strings anyway? If I try to do so, I get a compiler error. (I'm using Eclipse. I noticed that chars can be compared automatically).


Solution

  • int x =  0;
    int i= 0;
    int j = 0;
    while(i != list1.length && j != list2.length){
      int v = list1[i].compareTo(list2[j]);
      if (v == 0){
        x++;i++;j++;
      }else if (v < 0){
        i++;
      } else {
        j++;
      }
    }
    return x;
    

    This makes the straightforward assumption that the strings are sorted using String.compareTo which would make sense.