Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Average of remaining elements after removing K largest and K smallest elements from array
Next article icon

Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times

Last Updated : 29 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers and a positive integer K, the task is to find the last element present in the array obtained by repeatedly removing the first element of the array and appending it twice to the end of the array K times.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}, K = 5
Output: 5
Explanation:
Initially, the array is {1, 2, 3, 4, 5}. Following operations are performed K(= 5) number of times:
After the 1st operation, the array modifies to {2, 3, 4, 5, 1, 1}.
After the 2nd operation, the array modifies to {3, 4, 5, 1, 1, 2, 2}.
After the 3rd operation, the array modifies to {4, 5, 1, 1, 2, 2, 3, 3}.
After the 4th operation, the array modifies to {5, 1, 1, 2, 2, 3, 3, 4, 4}.
After the 5th operation, the array modifies to {1, 1, 2, 2, 3, 3, 4, 4, 5, 5}.
After completing the above operations, the last element is 5. Therefore, the answer is 5.

Input: arr[] = {1, 2, 3}, K = 7
Output: 2

Approach: The given problem can be solved by observing the following pattern:

Consider an array arr[] = {1, 2, 3, 4, 5}
After first 5 operations, the array modifies to {1, 1, 2, 2, 3, 3, 4, 4, 5, 5}.
After first 10 operations, the array modifies to {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5}.

Therefore, the size of the array after N * 2K operations is 2 * N * 2K.

Follow the steps below to solve the problem:

  • Iterate a loop from the value 0 using the variable j and update the value of K as (K - N * 2j) until K is greater than N * 2j.
  • After completing the above steps, initialize a variable, say r as 2j, where each value repeats itself R number of times.
  • Initialize a variable, say M as 1, that stores the index of the character in the array arr[] which is equal to the last character after performing K operations.
  • Iterate over the range [1, N] using the variable i and if the value of K is greater than R * i, then increment M by 1.
  • After completing the above steps, print the value of arr[M - 1] as the resultant last element of the array.

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 the last element // after performing given operations void findLastElement(int N, vector<int> A) {          // Length of the array     int l = A.size();      int j = 0;      // Increment j until     // condition is satisfied     while (N > l * (pow(2, j)))     {         N = N - l * pow(2, j);         j += 1;     }      int k = 1;      // In each pair every value is     // repeating r number of times     int r = pow(2, j);     for(int i = 1; i < l; i++)     {         if (N > r * i)             k += 1;     }      // Print the result according     // to the value of k     for(int i = 0; i < l; i++)     {         if (i + 1 == k)         {             cout << (A[i]);             return;         }     } }  // Driver Code int main() {          // Given K     int K = 7;          // Given arr[]     vector<int> A = { 1, 2, 3 };          // Function call     findLastElement(K, A);          return 0; }  // This code is contributed by mohit kumar 29 
Java
// Java program for the above approach import java.io.*; class GFG {        // Function to find the last element     // after performing given operations     static void findLastElement(int N, int[] A)     {          // Length of the array         int l = A.length;          int j = 0;          // Increment j until         // condition is satisfied         while (N > l * (int)(Math.pow(2, j))) {             N = N - l * (int)Math.pow(2, j);             j += 1;         }          int k = 1;          // In each pair every value is         // repeating r number of times         int r = (int)Math.pow(2, j);         for (int i = 1; i < l; i++) {             if (N > r * i)                 k += 1;         }          // Print the result according         // to the value of k         for (int i = 0; i < l; i++) {             if (i + 1 == k) {                 System.out.print(A[i]);                 return;             }         }     }      // Driver Code     public static void main(String[] args)     {          // Given K         int K = 7;          // Given arr[]         int[] A = { 1, 2, 3 };          // Function call         findLastElement(K, A);     } }  // This code is contributed by subham348. 
Python3
# Python program for the above approach  # Function to find the last element # after performing given operations def findLastElement(N, A):      # Length of the array     l = len(A)      j = 0      # Increment j until     # condition is satisfied     while(N > l*(2**j)):         N = N - l * 2**j         j += 1      k = 1      # In each pair every value is     # repeating r number of times     r = 2**j     for i in range(1, l):         if N > r * i:             k += 1      # Print the result according     # to the value of k     for i in range(0, len(A)):         if(i + 1 == k):             print(A[i])             return   # Driver Code if __name__ == '__main__':        # Given K     K = 7      # Given arr[]     A = [1, 2, 3]      # Function call     findLastElement(K, A) 
C#
// C# program for the above approach using System;  class GFG{      // Function to find the last element     // after performing given operations     static void findLastElement(int N, int[] A)     {           // Length of the array         int l = A.Length;           int j = 0;           // Increment j until         // condition is satisfied         while (N > l * (int)(Math.Pow(2, j))) {             N = N - l * (int)Math.Pow(2, j);             j += 1;         }           int k = 1;           // In each pair every value is         // repeating r number of times         int r = (int)Math.Pow(2, j);         for (int i = 1; i < l; i++) {             if (N > r * i)                 k += 1;         }           // Print the result according         // to the value of k         for (int i = 0; i < l; i++) {             if (i + 1 == k) {                 Console.WriteLine(A[i]);                 return;             }         }     }  // Driver Code public static void Main(String[] args) {     // Given K         int K = 7;           // Given arr[]         int[] A = { 1, 2, 3 };           // Function call         findLastElement(K, A); } }  // This code is contributed by target_62. 
JavaScript
<script>  // JavaScript program for the above approach   // Function to find the last element // after performing given operations function findLastElement(N, A) {          // Length of the array     let l = A.length;      let j = 0;      // Increment j until     // condition is satisfied     while (N > l * (Math.pow(2, j)))     {         N = N - l * Math.pow(2, j);         j += 1;     }      let k = 1;      // In each pair every value is     // repeating r number of times     let r = Math.pow(2, j);     for(let i = 1; i < l; i++)     {         if (N > r * i)             k += 1;     }      // Print the result according     // to the value of k     for(let i = 0; i < l; i++)     {         if (i + 1 == k)         {             document.write(A[i]);             return;         }     } }  // Driver Code          // Given K     let K = 7;          // Given arr[]     let A = [ 1, 2, 3 ];          // Function call     findLastElement(K, A);      </script> 

Output: 
2

 

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


Next Article
Average of remaining elements after removing K largest and K smallest elements from array

J

jatindscl015
Improve
Article Tags :
  • Misc
  • Greedy
  • Pattern Searching
  • Mathematical
  • DSA
  • Arrays
  • array-rearrange
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Misc
  • Pattern Searching

Similar Reads

  • Count all elements in the array which appears at least K times after their first occurrence
    Given an array arr[] of N integer elements and an integer K. The task is to count all distinct arr[i] such that arr[i] appears at least K times in the index range i + 1 to n - 1. Examples: Input: arr[] = {1, 2, 1, 3}, K = 1 Output: 1 arr[0] = 1 is the only element that appears at least once in the i
    15 min read
  • Sum of array elements possible by appending arr[i] / K to the end of the array K times for array elements divisible by K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the array elements possible by traversing the array and adding arr[i] / K, K number of times at the end of the array, if arr[i] is divisible by K. Otherwise, stop the traversal. Examples: Input: arr[] = {4
    14 min read
  • Convert an array into another by repeatedly removing the last element and placing it at any arbitrary index
    Given two arrays A[] and B[], both consisting of a permutation of first N natural numbers, the task is to count the minimum number of times the last array element is required to be shifted to any arbitrary position in the array A[] to make both the arrays A[] and B[] equal. Examples: Input: A[] = {1
    6 min read
  • Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
    Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies
    8 min read
  • Average of remaining elements after removing K largest and K smallest elements from array
    Given an array of N integers. The task is to find the average of the numbers after removing k largest elements and k smallest element from the array i.e. calculate the average value of the remaining N - 2K elements. Examples: Input: arr = [1, 2, 4, 4, 5, 6], K = 2Output: 4Remove 2 smallest elements
    5 min read
  • Queries to calculate average of an array after removing K smallest and largest elements with updates
    Given two positive integers N and K, initialize an empty array arr[] and Q number of queries of the following two types: addInteger(x): Insert element X in the array arr[]. If the size of the array becomes greater than N, then remove the element from the beginning of the array.calculateSpecialAverag
    15+ min read
  • Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K
    Given an array arr[] consisting of N integers and a positive integer K, the task is to check if the given array can be reduced to a single element by repeatedly removing the larger of the two elements present in a pair whose absolute difference is at most K. If the array can be reduced to a single e
    11 min read
  • Modify array by removing (arr[i] + arr[i + 1])th element exactly K times
    Given an array arr[] consisting of first N natural numbers, where arr[i] = i ( 1-based indexing ) and a positive integer K, the task is to print the array arr[] obtained after removing every (arr[i] + arr[i + 1])th element from the array in every ith operation exactly K times. Examples: Input: arr[]
    9 min read
  • Last element remaining after repeated removal of Array elements at perfect square indices
    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: 5Explanation:Following the removal of array element at perfect sq
    7 min read
  • Minimum increments to modify array such that value of any array element can be splitted to make all remaining elements equal
    Given an array arr[] consisting of N elements, the task is to find the minimum number of increments required to be performed on the given array such that after selecting any array element at any index and splitting its value to the other array elements makes all other N - 1 elements equal. Examples:
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences