Skip to content

Instantly share code, notes, and snippets.

@bmakarand2009
Created August 6, 2020 02:02
Show Gist options
  • Save bmakarand2009/7ba4b26fbb5b3e0a28deacd34f85dd7c to your computer and use it in GitHub Desktop.
Save bmakarand2009/7ba4b26fbb5b3e0a28deacd34f85dd7c to your computer and use it in GitHub Desktop.
package com.company;
/**
* Finder utitilies
*/
public class Finder {
/**
*
* @param smallArray Represents the subset array to be found
* @param bigArray Represents the set in which to find the array
* @return int This returns the index of the first element if subset of is found else -1
*/
public int find(char[] smallArray, char[] bigArray){
int result = -1;
//step1 boundary conditions
if(bigArray.length == 0 || smallArray.length ==0){
return result;
}
if(bigArray.length < smallArray.length) {
return result;
}
//small array is considered to be a block, so check till the start only
int len = bigArray.length - smallArray.length;
for (int i = 0; i <= len; i++) {
if( bigArray[i] == smallArray[0] && isSequence(smallArray, bigArray, i)){
return i;
}
}
return result;
}
private boolean isSequence(char[] smallArray, char[] bigArray, int index){
boolean isValid = true;
for (int i=1; i<smallArray.length; i++){
if(bigArray[index+i] != smallArray[i]){
isValid = false;
break;
}
}
return isValid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment