Last remaining element after repeated removal of odd indexed elements
Given a positive integer N, the task is to print the last remaining element from a sequence [1, N] after repeatedly removing all the odd-indexed elements from the sequence.
Examples:
Input: N = 4
Output: 4
Explanation:
Input: N = 9
Output: 8
Naive Approach: The naive approach to solve the above problem is to store the sequence. Iterate the sequence and remove the odd-indexed elements from it. Repeat the above steps till only one element remains.
Time Complexity: O(N logN)
Auxiliary Space: O(1)
Efficient Approach: Consider the below observation:
- In the first step, all the odd elements will be removed with a difference of 2
- In the second step, all even elements will be removed, starting from 2, with a difference 4
- In the second step, all even elements will be removed, starting from 4, with a difference 8
- Similarly, in the next step, all elements with difference 16 will be removed and so on.
- Therefore, in each step, you can see that the elements with difference 2X will be removed.
- In doing so, eventually all the elements will be removed except the largest power of 2 present in the sequence.
From the above observations, it can be deduced that:
last remaining element (L) = log2 N
Below is the implementation of the above approach.
C++
#include <iostream>
#include<math.h>
using namespace std;
int lastBlock( int N)
{
int largestPower = log2(N);
return pow (2,largestPower);
}
int main()
{
int N = 10;
cout << lastBlock(N);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int lastBlock( int N) {
int largestPower = ( int )(Math.log(N) / Math.log( 2 ));
return ( int )(Math.pow( 2 , largestPower));
}
public static void main(String[] args)
{
int N = 10 ;
System.out.println(lastBlock(N));
}
}
|
Python3
import math
def lastBlock(N):
largestPower = ( int )(math.log(N, 2 ))
return ( int )(math. pow ( 2 , largestPower))
N = 10
print (lastBlock(N))
|
C#
using System;
class GFG {
public static int lastBlock( int N) {
int largestPower = ( int )(Math.Log(N) / Math.Log(2));
return ( int )(Math.Pow(2, largestPower));
}
public static void Main(String[] args)
{
int N = 10;
Console.Write(lastBlock(N));
}
}
|
Javascript
<script>
function lastBlock(N) {
largestPower = Math.floor(Math.log2(N))
return Math.floor(Math.pow(2, largestPower))
}
let N = 10
document.write(lastBlock(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
16 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...