Find last element after deleting every second element in array of n integers in C++

C++Server Side ProgrammingProgramming

Consider we have one circular array containing integers from 1 to n. Find the last element, that would remain in the list after deleting every second element starting from first element. If the input is 5, then array will be [1, 2, 3, 4, 5]. Start from 1. After deleting each second element will be like −

1 0 3 4 5
1 0 3 0 5
0 0 3 0 5
0 0 3 0 0

So the element that remains in the list is 3.

We will solve this problem using recursion. Suppose n is even. The numbers 2, 4, 6 will be removed, then we will start from 1 again. So n/2 numbers are removed. And we start as if form 1 in an array of n/2 containing only odd digits 1, 3, 5, … n/2. So we can write the formula like −

solve(n)=2*solve(n/2)-1[when n is even]
solve(n)=2*solve(n-1/2)+1[when n is odd]

base condition is solve(1) = 1.

Example

#include<iostream>
using namespace std;
int deleteSecondElement(int n) {
   if (n == 1)
      return 1;
   if (n % 2 == 0)
      return 2 * deleteSecondElement(n / 2) - 1;
   else
      return 2 * deleteSecondElement(((n - 1) / 2)) + 1;
}
int main() {
   int n = 5;
   cout << "Remaining Element: " << deleteSecondElement(n) << endl;
   n = 10;
   cout << "Remaining Element: " << deleteSecondElement(n) << endl;
}

Output

Remaining Element: 3
Remaining Element: 5
raja
Published on 01-Nov-2019 10:12:04
Advertisements