Find the position of the last removed element from the array using C++


In this problem, we are given an array arr[] of size N and an integer value M. Our task is to find the position of the last removed element from the array.

The removal of values from the array is based on the operations −

  • For an element in the array arr[i]. If arr[i] > M, pop the value and push arr[i] - M to the end of the array. Otherwise remove it from the array.

Perform the operations till the array consists of elements.

Let’s take an example to understand the problem,

Input

arr[] = {5, 4, 8}, M = 3

Output

3

Explanation

Removing values using operations,
{5, 4, 8} -> {4, 8, 2} -> {8, 1, 2} -> {1, 2, 5} -> {2, 5} -> {5} -> {2} ->
empty array.
The last value removed is 8, position is 3.

Solution Approach

A simple solution to the problem is by finding the last value to be removed using the fact that each value which will be removed last has the largest value of ceil(arr[i] / M).

To find the position of elements that exits the array last, we will traverse the array and store the position with maximum value of ceil(arr[i] / M).

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findLastRemPos(int arr[], int n, int m){
   for (int i = 0; i < n; i++) {
      arr[i] = (arr[i] / m + (arr[i] % m != 0));
   }
   int lastRemPos = -1, largestVal = -1;
   for (int i = n - 1; i >= 0; i--) {
      if (largestVal < arr[i]) {
         largestVal = arr[i];
         lastRemPos = i;
      }
   }
   return lastRemPos + 1;
}
int main(){
   int arr[] = {5, 4, 8, 1};
   int n = sizeof(arr) / sizeof(arr[0]);
   int m = 3;
   cout<<"The position of last removed element in the array is "<<findLastRemPos(arr, n, m);
   return 0;
}

Output

The position of last removed element in the array is 3

Updated on: 11-Feb-2022

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements