Skip to content

Instantly share code, notes, and snippets.

@kBashar
Last active August 29, 2015 14:07
Show Gist options
  • Save kBashar/1418cfa5d40ba4f2ecd9 to your computer and use it in GitHub Desktop.
Save kBashar/1418cfa5d40ba4f2ecd9 to your computer and use it in GitHub Desktop.
‪#‎Javafest_Brain_Tweaker‬ # 1 from https://www.facebook.com/therapjavafest/posts/591777984278321
Find an Array
Implement a method that given two arrays as parameters will find the starting index where the second parameter occurs as a sub-array in the array given as the first parameter.
Your implementations should return -1 if the sub-array cannot be found.
Your implementation must implement the FindArray interface given bellow:
public interface FindArray {
int findArray(int[] array, int[] subArray);
}
Sample Input:
[4,9,3,7,8] and [3,7] should return 2.
[1,3,5] and [1] should return 0.
[7,8,9] and [8,9,10] should return -1.
Sample Code :
public class MyFindArray implements FindArray {
public int findArray(int[] array, int[] subArray) {
return -1;
}
}
public interface FindArray {
int findArray(int[] array, int[] subArray);
}
import java.util.Arrays;
/**
* Created by ahmed on 10/16/2014.
*/
public class SubArray implements FindArray {
@Override
public int findArray(int[] array, int[] subArray) {
int firstArrayLength = array.length;
int secondArrayLength = subArray.length;
if (firstArrayLength == secondArrayLength) {
return Arrays.equals(array, subArray) ? 0 : -1;
} else if (firstArrayLength > secondArrayLength) {
boolean flag = false;
for (int i = 0, j = firstArrayLength; j >= secondArrayLength; i++, j--) {
if (hasSubArray(array, subArray, i, i + secondArrayLength)) {
flag = true;
return i;
}
}
if (!flag) return -1;
} else {
return -1;
}
return 0;
}
private boolean hasSubArray(int[] array, int[] subArray,
int from, int to) {
int[] tempArray = Arrays.copyOfRange(array, from, to);
return Arrays.equals(tempArray, subArray);
}
// for test purpose
public static void main(String[] args) {
SubArray subArray = new SubArray();
int[] array = {1,3,5};
int[] sub_array = {1};
System.out.println(subArray.findArray(array, sub_array));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment