Challenge: Brute Force Searching II

Learn how the brute force search can be used to find the last and kth-last occurrence (i.e., the kth occurrence counting backward) in an array.

Search problems

In this lesson, we will learn to solve multiple search problems using arrays. Write your code in the playground here. We have provided you the main() function and all the required prototypes of the functions. Uncomment the code lines in the main() function after each task is done, and test whether your program is working correctly or not.

Exercise playground

Please write your code in the given playground.

2 1 2 2 3 2 4 5 2 1 -1
Exercise playground with all the function prototypes

Exercise 1: Search the last occurrence

Task: Find the last index of a specific element in an array.

Sample Program

        Program: Searching problems

Data: { 2 1 3 2 4 5 2 1 }


------------------------------------------

Searching the last occurrence of: 2
2 is found at index:6

Let’s make the function:

int findLastOccurrence(int D[], int size, int t)

Directions: There are two possible implementations.

  1. Iterate through the array and keep checking whenever the value is found. Save that index and keep moving forward and updating the index. After the iteration, the saved index will be the last updated value, which is the last occurrence of the searched value.

  2. The second idea is to iterate from the last index of an array to the first index. Whenever the first instance of the element is found, return that index. Otherwise, return -1.

Instruction: Write the code of findLastOccurrence() in the above playground and test it by uncommenting the lines in the main() function.

Exercise 2: Search the kth-last occurrence

Task: Find the index of the kth-last occurrence of an element in an array.

Sample input

        Program: Searching problems

Data: { 2 1 2 2 3 2 4 5 2 1 }


------------------------------------------

Searching the K'th Occurrence(from the end) of: 2
K: 2
2 is found at: 5

Exercise:

int findKthLastIndex(int D[], int size, int k, int t)

Instruction: Write the code of findKthLastIndex() in the exercise playground and test it.