Skip to content
Related Articles

Related Articles

Improve Article

Last element remaining after repeated removal of Array elements at perfect square indices

  • Difficulty Level : Hard
  • Last Updated : 02 Sep, 2021
Geek Week

Given an array arr[](1-based indexing) consisting of N integers, the task is to find the last element remaining element after repeated removal of array element at perfect square indices.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}
Output: 5
Explanation:
Following the removal of array element at perfect square indices that are performed:

  • Removing array elements at indices 1 and 4 modifies the array to {2, 3, 5}.
  • Removing array elements at indices 1 modifies the array to {3, 5}.
  • Removing array elements at indices 1 modifies the array to {5}.

After performing the above operations, the array element remains is 5. Therefore, print 5. 

Input: arr[] = {2, 3, 4, 4, 2, 4, -3, 1, 1}
Output: -3



 

Naive Approach: The given problem can be solved by removing the array elements at perfect square indices and then copy all the elements to the new array. Keep performing this step until only one element remains in the array. After completing the above steps, print the last element that remains.

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

Efficient Approach: The above approach can also be optimized by finding the potential last remaining array elements until that element is not present at perfect square indices. Follow the steps below to solve the given problem:

  • Initialize a variable, say ans as N that stores the last remaining indices after performing the given operations.
  • Iterate until the value of N is greater than 1 and perform the following steps:
    • Find the count of elements that can be discarded, say D as sqrt(N).
    • If the square of D is N then N can’t be the last remaining element as it is removed. So decrement the value of ans by 1 as the next potential remaining indices.
    • Decrement the value of N by D.
  • After completing the above steps, print the element at index (D – 1) as the remaining possible element.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find last remaining index
// after repeated removal of perfect
// square indices
int findRemainingIndex(int N)
{
    // Initialize the ans variable as N
    int ans = N;
 
    // Iterate a while loop and discard
    // the possible values
    while (N > 1) {
 
        // Total discarded values
        int discard = int(sqrt(N));
 
        // Check if this forms a
        // perfect square
        if (discard * discard == N) {
 
            // Decrease answer by 1
            ans--;
        }
 
        // Subtract the value from
        // the current value of N
        N -= discard;
    }
 
    // Return the value remained
    return ans;
}
 
// Function to find last remaining element
// after repeated removal of array element
// at perfect square indices
void findRemainingElement(int arr[], int N)
{
 
    // Find the remaining index
    int remainingIndex = findRemainingIndex(N);
 
    // Print the element at that
    // index as the result
    cout << arr[remainingIndex - 1];
}
 
// Driver Code
signed main()
{
    int arr[] = { 2, 3, 4, 4, 2, 4, -3, 1, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    findRemainingElement(arr, N);
 
    return 0;
}

Java




// Java implementation of the above approach
import java.util.*;
import java.lang.*;
import java.lang.Math;
class GFG {
 
// Function to find last remaining index
// after repeated removal of perfect
// square indices
static int findRemainingIndex(int N)
{
   
    // Initialize the ans variable as N
    int ans = N;
  
    // Iterate a while loop and discard
    // the possible values
    while (N > 1) {
  
        // Total discarded values
        int discard = (int)(Math.sqrt(N));
  
        // Check if this forms a
        // perfect square
        if (discard * discard == N) {
  
            // Decrease answer by 1
            ans--;
        }
  
        // Subtract the value from
        // the current value of N
        N -= discard;
    }
  
    // Return the value remained
    return ans;
}
  
// Function to find last remaining element
// after repeated removal of array element
// at perfect square indices
static void findRemainingElement(int arr[], int N)
{
  
    // Find the remaining index
    int remainingIndex = findRemainingIndex(N);
  
    // Print the element at that
    // index as the result
    System.out.print(arr[remainingIndex - 1]);
}
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given input
         int arr[] = { 2, 3, 4, 4, 2, 4, -3, 1, 1 };
        int N = 9;
        findRemainingElement(arr, N);
     
    }
}
// This code is contributed by dwivediyash

Python3




# Python 3 program for the above approach
from math import sqrt
 
# Function to find last remaining index
# after repeated removal of perfect
# square indices
def findRemainingIndex(N):
    # Initialize the ans variable as N
    ans = N
 
    # Iterate a while loop and discard
    # the possible values
    while (N > 1):
        # Total discarded values
        discard = int(sqrt(N))
 
        # Check if this forms a
        # perfect square
        if (discard * discard == N):
            # Decrease answer by 1
            ans -= 1
 
        # Subtract the value from
        # the current value of N
        N -= discard
 
    # Return the value remained
    return ans
 
# Function to find last remaining element
# after repeated removal of array element
# at perfect square indices
def findRemainingElement(arr, N):
   
    # Find the remaining index
    remainingIndex = findRemainingIndex(N)
 
    # Print the element at that
    # index as the result
    print(arr[remainingIndex - 1])
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 4, 4, 2, 4, -3, 1, 1]
    N = len(arr)
    findRemainingElement(arr, N)
     
    # This code is contributed by SURENDRA_GANGWAR.

C#




// C# program for the above approach
using System;
 
class GFG {
 
// Function to find last remaining index
// after repeated removal of perfect
// square indices
static int findRemainingIndex(int N)
{
   
    // Initialize the ans variable as N
    int ans = N;
  
    // Iterate a while loop and discard
    // the possible values
    while (N > 1) {
  
        // Total discarded values
        int discard = (int)(Math.Sqrt(N));
  
        // Check if this forms a
        // perfect square
        if (discard * discard == N) {
  
            // Decrease answer by 1
            ans--;
        }
  
        // Subtract the value from
        // the current value of N
        N -= discard;
    }
  
    // Return the value remained
    return ans;
}
  
// Function to find last remaining element
// after repeated removal of array element
// at perfect square indices
static void findRemainingElement(int[] arr, int N)
{
  
    // Find the remaining index
    int remainingIndex = findRemainingIndex(N);
  
    // Print the element at that
    // index as the result
    Console.Write(arr[remainingIndex - 1]);
}
  
 
    // Driver Code
    public static void Main()
    {
        // Given input
         int[] arr = { 2, 3, 4, 4, 2, 4, -3, 1, 1 };
        int N = 9;
        findRemainingElement(arr, N);
    }
}
 
// This code is contributed by code_hunt.

Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
 
        // Function to find last remaining index
        // after repeated removal of perfect
        // square indices
        function findRemainingIndex(N) {
            // Initialize the ans variable as N
            let ans = N;
 
            // Iterate a while loop and discard
            // the possible values
            while (N > 1) {
 
                // Total discarded values
                let discard = Math.floor(Math.sqrt(N));
 
                // Check if this forms a
                // perfect square
                if (discard * discard == N) {
 
                    // Decrease answer by 1
                    ans--;
                }
 
                // Subtract the value from
                // the current value of N
                N -= discard;
            }
 
            // Return the value remained
            return ans;
        }
 
        // Function to find last remaining element
        // after repeated removal of array element
        // at perfect square indices
        function findRemainingElement(arr, N) {
 
            // Find the remaining index
            let remainingIndex = findRemainingIndex(N);
 
            // Print the element at that
            // index as the result
            document.write(arr[remainingIndex - 1]);
        }
 
        // Driver Code
 
        let arr = [2, 3, 4, 4, 2, 4, -3, 1, 1];
        let N = arr.length;
        findRemainingElement(arr, N);
 
 
// This code is contributed by Potta Lokesh
    </script>

 
 

Output: 
-3

 

 

Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)

 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :