← all problems

secondOccurrenceIndex 🌶️🌶️🌶️

Write a method that takes two String parameters, text and target, and returns the index in text where the SECOND occurrence of target begins. For example, secondOccurrenceIndex("banana", "an") should return 3 ("an" occurs at index 1 and again at index 3, and it is the second one you want).

Preconditions: target occurs at least twice in text, and that no two occurrences overlap.

Note that the AP Java subset gives you only the one-argument indexOf, which always searches from the beginning, so you cannot simply ask it to start looking partway through. Use substring to narrow down what you search, then work out what that result means as an index into the original text.