patternjavaMinor
Finding common strings among 2 arrays of strings of length 1, sorted alphabetically in O(n) time complexity
Viewed 0 times
amongarrayslengthtimealphabeticallyfindingsortedstringscommoncomplexity
Problem
The problem:
Start with two arrays of strings, a and b, each in alphabetical order,
possibly with duplicates. Return the count of the number of strings
which appear in both arrays.
I tried to solve the problem with \$O(n)\$ time complexity:
It seems to be working but the code looks somewhat ugly. Please feel free to review or if you have any other elegant solution would appreciate you include it in the review.
Start with two arrays of strings, a and b, each in alphabetical order,
possibly with duplicates. Return the count of the number of strings
which appear in both arrays.
commonTwo({"a", "c", "x"}, {"b", "c", "d", "x"}) → 2commonTwo({"a", "c", "x"}, {"a", "b", "c", "x", "z"}) → 3commonTwo({"a", "b", "c"}, {"a", "b", "c"}) → 3I tried to solve the problem with \$O(n)\$ time complexity:
public int commonTwo(String[] a, String[] b) {
int result=0;
String prev="";
for(int i=0,j=0;(i<a.length)&&(j<b.length);)
{
if(a[i].charAt(0)<b[j].charAt(0))
{
i++;
continue;
}
if(a[i].charAt(0)==b[j].charAt(0))
{
if(!(a[i].equals(prev)))
result++;
prev=a[i];
i++; j++;
continue;
}
j++;
}
return result;
}It seems to be working but the code looks somewhat ugly. Please feel free to review or if you have any other elegant solution would appreciate you include it in the review.
Solution
Java is not my strong-point, but there are a few things that stand out.
-
There are unnecessary parentheses, e.g. in
and
-
Optional braces should always be included, e.g. in
-
Statements should always be on separate lines, e.g. don't do
There is a more elegant solution using a
- Spacing is non-standard.
-
There are unnecessary parentheses, e.g. in
(i<a.length)&&(j<b.length)and
if(!(a[i].equals(prev)))-
Optional braces should always be included, e.g. in
if(!(a[i].equals(prev)))
result++;-
Statements should always be on separate lines, e.g. don't do
i++; j++;There is a more elegant solution using a
HashSet, which I believe has the same time complexity.public int commonTwo(String[] a, String[] b) {
Set common = new HashSet<>(Arrays.asList(a));
common.retainAll(new HashSet<>(Arrays.asList(b)));
return common.size();
}Code Snippets
(i<a.length)&&(j<b.length)if(!(a[i].equals(prev)))if(!(a[i].equals(prev)))
result++;public int commonTwo(String[] a, String[] b) {
Set<String> common = new HashSet<>(Arrays.asList(a));
common.retainAll(new HashSet<>(Arrays.asList(b)));
return common.size();
}Context
StackExchange Code Review Q#57010, answer score: 6
Revisions (0)
No revisions yet.