-1

I am trying to write a recursive function to check whether one array is contained in a second array (my example is also sub-array) and returns true or false.

For example: [d, e] is contained in [a, b​​, c, d, e, f]

.

I know how to check without recursion (using for loops), but can not think of a solution using recursion.

3
  • 5
    What is your solution without recursion? Commented Jun 5, 2012 at 8:50
  • This question has already been answered here: stackoverflow.com/questions/3940194/… Commented Jun 5, 2012 at 9:28
  • i cannot use loops only recursion Commented Jun 5, 2012 at 10:03

2 Answers 2

1

The principle is the following:

0) If the first array is longer than the second one, it's not a subarray.

1) If the second array begins with the first (like [a,b] and [a,b,c,d]), then it's a subarray.

2) Else: If the first array is a subarray of the tail of the second one (that means, the part after the first element), then it's a subarray.

Just to be sure: tail([a,b,c,d]) == [b,c,d] (since I don't know how that's called in Java.)

Sign up to request clarification or add additional context in comments.

1 Comment

I assumed the OP was looking for a subarray, not a subset - so actually the first one being an infix of the second one. That really isn't clear exactly from the quaestion, though he mentioned subarray explicitly in the description - that's why I chose this algo. I'll try to clarify this.
0

You can use hashing to store elements of large array in hash table and then check whether each element of sub array is there in hash table or not, If all elements found then it will be subarray.

1 Comment

A sub-array has a very exacting definition. [b c] is a sub-array of [a b c d], but [c b] is not. It is important that the elements be such that the sub array is a 'part' of the array.

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.