Given a positive integer **N**, the task is to print the last remaining element from a sequence **[1, N]** after repeatedly performing the following operations in the given order alternately:

- Remove all the odd-indexed elements from the sequence.
- Remove all the even-indexed elements from the sequence.

**Examples:**

Input:N = 9Output:6Explanation:

Sequence = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Step 1: Removing odd-indexed elements modifies sequence to {2, 4, 6, 8}

Step 2: Removing even-indexed elements modifies sequence to {2, 6}

Step 3: Removing odd-indexed elements modifies sequence to {6}

Therefore, the last remaining element is 6.

Input:N = 5Output:2Explanation:

Sequence = {1, 2, 3, 4, 5}

Step 1: Removing odd-indexed elements modifies sequence to {2, 4}

Step 2: Removing even-indexed elements modifies sequence to {2}

Therefore, the last remaining element is 2.

**Naive Approach:** The simplest approach is to store all the elements from **1** to **N** sequentially in an array. For every operation, remove elements from the array and shift the remaining elements towards the left. After reducing the array to a single element, print that remaining element as the required answer.

**Time Complexity:** O(N^{2}*log N)**Auxiliary Space:** O(N)

**Efficient Approach:** The above approach can be optimized using Dynamic Programming.

The recurrence relation is as follows:

where,

iis in the range [1, N]dp[i]stores the answer when the array elements are from 1 to i.

Follow the steps below to solve the problem:

- Initialize an array
**dp[]**where**dp[i]**stores the remaining element or the sequence**[1, i]**. - For the base condition of
**i = 1**, print**1**as the required answer. - Calculate the value of
**dp[N]**using the aforementioned recurrence relation and use the already computed subproblems to avoid recomputation of overlapping subproblems. - After completing the above steps, print the value of
**dp[N]**as the result.

Below is the implementation of the above approach:

## C++14

`// C++14 program for the above approach` `#include <bits/stdc++.h>` `using` `namespace` `std;` `// Function to calculate the last` `// remaining element from the sequence` `int` `lastRemaining(` `int` `n, map<` `int` `, ` `int` `> &dp)` `{` ` ` ` ` `// If dp[n] is already calculated` ` ` `if` `(dp.find(n) != dp.end())` ` ` `return` `dp[n];` ` ` `// Base Case:` ` ` `if` `(n == 1)` ` ` `return` `1;` ` ` ` ` `// Recursive call` ` ` `else` ` ` `dp[n] = 2 * (1 + n / 2 - ` ` ` `lastRemaining(n / 2, dp));` ` ` `// Return the value of dp[n]` ` ` `return` `dp[n];` `}` `// Driver Code` `int` `main()` `{` ` ` ` ` `// Given N` ` ` `int` `N = 5;` ` ` ` ` `// Stores the` ` ` `map<` `int` `, ` `int` `> dp;` ` ` ` ` `// Function call` ` ` `cout << lastRemaining(N, dp);` ` ` ` ` `return` `0;` `}` `// This code is contributed by mohit kumar 29` |

*chevron_right*

*filter_none*

## Java

`// Java program for ` `// the above approach` `import` `java.util.*;` `class` `GFG{` `// Function to calculate the last` `// remaining element from the sequence` `static` `int` `lastRemaining(` `int` `n, HashMap<Integer,` ` ` `Integer> dp)` `{` ` ` `// If dp[n] is already calculated` ` ` `if` `(dp.containsKey(n))` ` ` `return` `dp.get(n);` ` ` `// Base Case:` ` ` `if` `(n == ` `1` `)` ` ` `return` `1` `;` ` ` `// Recursive call` ` ` `else` ` ` `dp.put(n, ` `2` `* (` `1` `+ n / ` `2` `-` ` ` `lastRemaining(n / ` `2` `, dp)));` ` ` `// Return the value of dp[n]` ` ` `return` `dp.get(n);` `}` `// Driver Code` `public` `static` `void` `main(String[] args)` `{ ` ` ` `// Given N` ` ` `int` `N = ` `5` `;` ` ` `// Stores the` ` ` `HashMap<Integer,` ` ` `Integer> dp = ` `new` `HashMap<Integer, ` ` ` `Integer>();` ` ` `// Function call` ` ` `System.out.print(lastRemaining(N, dp));` `}` `}` `// This code is contributed by Princi Singh` |

*chevron_right*

*filter_none*

## Python3

`# Python program for the above approach` `# Function to calculate the last` `# remaining element from the sequence` `def` `lastRemaining(n, dp):` ` ` `# If dp[n] is already calculated` ` ` `if` `n ` `in` `dp:` ` ` `return` `dp[n]` ` ` `# Base Case:` ` ` `if` `n ` `=` `=` `1` `:` ` ` `return` `1` ` ` `# Recursive Call` ` ` `else` `:` ` ` `dp[n] ` `=` `2` `*` `(` `1` `+` `n` `/` `/` `2` ` ` `-` `lastRemaining(n` `/` `/` `2` `, dp))` ` ` `# Return the value of dp[n]` ` ` `return` `dp[n]` `# Driver Code` `# Given N` `N ` `=` `5` `# Stores the ` `dp ` `=` `{}` `# Function Call` `print` `(lastRemaining(N, dp))` |

*chevron_right*

*filter_none*

## C#

`// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;` `class` `GFG{` `// Function to calculate the last` `// remaining element from the sequence` `static` `int` `lastRemaining(` `int` `n, Dictionary<` `int` `,` ` ` `int` `> dp)` `{` ` ` ` ` `// If dp[n] is already calculated` ` ` `if` `(dp.ContainsKey(n))` ` ` `return` `dp[n];` ` ` ` ` `// Base Case:` ` ` `if` `(n == 1)` ` ` `return` `1;` ` ` ` ` `// Recursive call` ` ` `else` ` ` `dp.Add(n, 2 * (1 + n / 2 -` ` ` `lastRemaining(n / 2, dp)));` ` ` ` ` `// Return the value of dp[n]` ` ` `return` `dp[n];` `}` `// Driver Code` `public` `static` `void` `Main(String[] args)` `{ ` ` ` ` ` `// Given N` ` ` `int` `N = 5;` ` ` ` ` `// Stores the` ` ` `Dictionary<` `int` `,` ` ` `int` `> dp = ` `new` `Dictionary<` `int` `, ` ` ` `int` `>();` ` ` ` ` `// Function call` ` ` `Console.Write(lastRemaining(N, dp));` `}` `}` `// This code is contributed by Princi Singh` |

*chevron_right*

*filter_none*

**Output:**

2

**Time Complexity:** O(N)**Auxiliary Space:** O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Maximize sum of remaining elements after every removal of the array half with greater sum
- Find a number K having sum of numbers obtained by repeated removal of last digit of K is N
- Find last two remaining elements after removing median of any 3 consecutive elements repeatedly
- Find last remaining element after reducing the Array
- Program to print product of even and odd indexed elements in an Array
- Absolute Difference of even and odd indexed elements in an Array
- Modify given array to make sum of odd and even indexed elements same
- Maximum sum of even indexed elements obtained by right shift on an even sized subarray
- Rearrange array such that all even-indexed elements in the Array is even
- Delete odd and even numbers at alternate step such that sum of remaining elements is minimized
- Check if the last element of array is even or odd after performing a operation p times
- Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal
- Maximum removal from array when removal time >= waiting time
- Minimum peak elements from an array by their repeated removal at every iteration of the array
- Find Nth term of the series where each term differs by 6 and 2 alternately
- Average of remaining elements after removing K largest and K smallest elements from array
- Cost required to empty a given array by repeated removal of maximum obtained by given operations
- Even numbers at even index and odd numbers at odd index
- Count of integers in a range which have even number of odd digits and odd number of even digits
- Check if a number has an odd count of odd divisors and even count of even divisors

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.