
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find last element after deleting every second element in array of n integers in C++
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
- Related Articles
- Select every element that is the second element of its parent, counting from the last child
- Maximum possible middle element of the array after deleting exactly k elements in C++
- Find the second most frequent element in array JavaScript
- Kth smallest element after every insertion in C++
- First element and last element in a JavaScript array?
- Program to find longest subarray of 1s after deleting one element using Python
- Find closest value for every element in array in C++
- Find the first repeating element in an array of integers C++
- Style every element that is the last element of its parent with CSS
- Floor of every element in same array in C++
- Find First and Last Position of Element in Sorted Array in Python
- How to find last occurence of element in the array in TypeScript?
- Find closest greater value for every element in array in C++
- Find closest smaller value for every element in array in C++
- Find difference between first and second largest array element in Java

Advertisements