2

I am new to java. I have a problem that, I have two arrays parentArray and subArray:

  • parentArray has values, {1,4,4,3,6}
  • subArray has values {4,4,3}

So, the second array or so-called subArray values are included in the first-array the so-called parentArray, with indexes starting from [1,2,3]. My question is how can we return the index value of the first element of subArray which is also part of parentArray.

i.e.

int[] parentArray = new int[]{1,4,4,3,6};
int[] subArray = new int[]{4,4,3};

As subArray's values are in parentArray starting index from [1], I want my program to return 1.

I have tried comparing two arrays and returning the common elements from both arrays. But ahead of that, I can not think any of logic as I am a beginner.

3 Answers 3

3

you can use the Collections.indexOfSubList() as follows:

List<Integer> parentArray = Arrays.asList(1,4,4,3,6);
List<Integer> subArray = Arrays.asList(4,4,3);

int index = Collections.indexOfSubList(parentArray , subArray);
// index is 1

if you want to implement for arrays, check out the source from that and modify it a bit:

public static int indexOfSubList(int[] source, int[] target) {
  int sourceSize = source.length;
  int targetSize = target.length;
  int maxCandidate = sourceSize - targetSize;

  nextCand:
    for (int candidate = 0; candidate <= maxCandidate; candidate++) {
      for (int i=0, j=candidate; i<targetSize; i++, j++)
        if (!(target[i] == source[j]))
          continue nextCand;  // Element mismatch, try next cand
      return candidate;  // All elements of candidate matched target
    }
  return -1;  // No candidate matched the target
}

usage:

int[] parentArray = new int[]{1,1,1,4,4,3,6};
int[] subArray = new int[]{4,4,3};
int index = indexOfSubList(parentArray, subArray);
// index is 3
System.out.println(index);
Sign up to request clarification or add additional context in comments.

5 Comments

Can I implement this with Array? not with List<>? Because my program has two methods one is main and another is for the logic, and that second method would have parameters as int parentArray[ ] and subArray[ ].
Actually, I came across to this code, from StackOverflow and GitHub only but it keeps returning 0. Thanks
when 0 is returned that means your matching subList start at the index 0
Sorry, my writing mistake. The console is returning saying Process finished with exit code 0 and still not getting output.
hmm interesting, i tried it, and it works, of course i did not add the System.out.println(index); just until now, maybe you missed that
3

I've created a method for this. Try below code,

public int checkSubArray(int[] parentArray, int[] subArray) {
    int result = -1;
    for (int i = 0; i < parentArray.length; i++) {
        int[] temp = Arrays.copyOfRange(parentArray, i, (subArray.length + i)); //This will create a temporary sub array
        if (Arrays.equals(temp, subArray)) {
            System.out.println(i);
            result = i;
        }
    }
    return result;
}

Improved Answer

public int checkSubArray(int[] parentArray, int[] subArray) {
    int result = -1;
    for (int i = 0; i < parentArray.length; i++) {
        if (parentArray[i] == subArray[0]) { // Checking if the first value matches
            int[] temp = Arrays.copyOfRange(parentArray, i, (subArray.length + i)); // This will create a temporary sub array
            if (Arrays.equals(temp, subArray)) {
                System.out.println(i);
                result = i;
            }
        }
    }
    return result;
}

5 Comments

Note that this will generate a lot of unnecessary arrays, at least checking if the first value match, then generate a subset.
Thanks @AxelH. I've improved my answer.
Yes, it's working fine but quick question what if the first array has not all the elements of the second array. Then it should return -1. Though we are storing -1 in int result but still no output.
@VivekDharek what value do you need to return when there is no match? Just check in your main method result is equal to -1 or not. ex: if(result!=-1)
BTW, you can stop at i <= parentArray.length - subArray.length ;) no need to check the 2 last value if you search for a subset of 3.
1

You could also try something like this if your array only contains integers less than 10.

public static void main(String[] args) {

    int[] parentArray = new int[]{1, 4, 4, 3, 6};
    int[] subArray = new int[]{4, 4, 3};

    String s1 = convertToString(parentArray);

    String s2 = convertToString(subArray);

    System.out.print(s1.indexOf(s2));
}

private static String convertToString(int[] array) {

    StringBuilder stringBuilder = new StringBuilder();

    for(int num : array){
        stringBuilder.append(num);
    }
    return stringBuilder.toString();
}

3 Comments

And now, try with values bigger than 9 ;) This could be adapt to use a String something like using Arrays.toString instead of your concatenation, then when you have the index of the match, you count the number of , but this would be an extreme solution...
This is not a solution. Check with this sample . You get a result of 6 where this should return 1...
Oh! Yes, I haven't thought of that. Can you explain why it is returning 6? Despite the second array is starting from 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.