In Python: Given two arrays of ints sorted in increasing order, outer and inner
ID: 3595236 • Letter: I
Question
In Python:
Given two arrays of ints sorted in increasing order, outer and inner, return true if all of the numbers in inner appear in outer. The best solution makes only a single "linear" pass of both arrays, taking advantage of the fact that both arrays are already in sorted order.
Given two arrays of ints sorted in increasing order, outer and inner, return true if all of the numbers in inner appear in outer. The best solution makes only a single "linear" pass of both arrays, taking advantage of the fact that both arrays are already in sorted order.
linearIn([1, 2, 4, 6], [2, 4]) true
linearIn([1, 2, 4, 6], [2, 3, 4]) false
linearIn([1, 2, 4, 4, 6], [2, 4]) true
Explanation / Answer
Use this method it will return result as you expected in your question :
public boolean linearIn(int[] outer, int[] inner) {
int i = 0;
int j = 0;
while(i < inner.length && j < outer.length) {
if(inner[i] > outer[j]) {
j++;
} else if(inner[i] < outer[j]) {
return false;
} else {
i++;
}
}
if(i != inner.length)
{
return false;
}else{
return true;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.