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:
Program to find the minimum (or maximum) element of an array
Next article icon

Find the Array element left after alternate removal of minimum and maximum

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array Arr of length N, it is reduced by 1 element at each step. Maximum and Minimum elements will be removed in alternating order from the remaining array until a single element is remaining in the array. The task is to find the remaining element in the given array.

Examples:

Input: arr[] = {1, 5, 4, 2}
Output: 2
Explanation: 
Remove Max element i.e., 5 arr[] = {1, 4, 2}
Remove Min element i.e., 1 arr[] = {4, 2}
Remove Max element i.e., 4 arr[] = {2}

Input: arr[] = {5, 10}
Output: 5

Approach:

Follow the below idea to solve the problem:

The idea is to sort the array and return the middle element as all of the right and left elements will be removed in the process.

Follow the below steps to solve this problem:

  • If N =1, return arr[0]
  • Sort the array arr[]
  • Return the middle element of the array i.e., arr[(N-1)/2]

Below is the implementation of the above approach:

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to find the element left int lastRemaining(int arr[], int N) {     // If single element in array     if (N == 1)         return arr[0];      // Sort the array     sort(arr, arr + N);      // return middle element     return arr[(N - 1) / 2]; }  // Driver Code int main() {     int arr[] = { 1, 5, 4, 2 };     int N = sizeof(arr) / sizeof(arr[0]);      // Function call     cout << lastRemaining(arr, N) << endl;     return 0; } 
Java
// Java code to implement the approach import java.util.*;  class GFG {      // Function to find the element left     static int lastRemaining(int arr[], int N)     {         // If single element in array         if (N == 1)             return arr[0];          // Sort the array         Arrays.sort(arr);          // return middle element         return arr[(N - 1) / 2];     }     // Driver Code     public static void main(String[] args)     {         int arr[] = { 1, 5, 4, 2 };         int N = arr.length;          // Function call         System.out.print(lastRemaining(arr, N));     } }  // This code is contributed by sanjoy_62. 
Python3
# Python code to implement the approach  # Function to find the element left def lastRemaining(arr, N):          # If single element in array     if (N == 1):         return arr[0]      # Sort the array     arr.sort()      # return middle element     return arr[(N - 1) // 2]  # Driver Code arr = [ 1, 5, 4, 2 ] N = len(arr)  # Function call print(lastRemaining(arr, N))  # This code is contributed by athakur42u. 
C#
// C# code to implement the approach using System; class GFG {      // Function to find the element left     static int lastRemaining(int[] arr, int N)     {          // If single element in array         if (N == 1)             return arr[0];          // Sort the array         Array.Sort(arr);          // return middle element         return arr[(N - 1) / 2];     }      // Driver code     public static void Main(string[] args)     {         int[] arr = { 1, 5, 4, 2 };         int N = arr.Length;          // Function call         Console.Write(lastRemaining(arr, N));     } }  // This code is contributed by code_hunt. 
JavaScript
 <script>         // JS code to implement the approach          // Function to find the element left         function lastRemaining(arr, N)         {                      // If single element in array             if (N == 1)                 return arr[0];              let x = Math.floor((N - 1) / 2);             // Sort the array             arr.sort(function (a, b) { return a - b })              // return middle element             return arr[x];         }          // Driver Code         let arr = [1, 5, 4, 2];         let N = arr.length;          // Function call         document.write(lastRemaining(arr, N));  // This code is contributed by lokeshpotta20.     </script> 

Output
2

Time Complexity: O(N * log(N)), for sorting the given array of size N.
Auxiliary Space: O(1), as constant extra space is required.


Next Article
Program to find the minimum (or maximum) element of an array
author
akashjha2671
Improve
Article Tags :
  • Greedy
  • Sorting
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Greedy
  • Sorting

Similar Reads

  • Leftmost and rightmost indices of the maximum and the minimum element of an array
    Given an array arr[], the task is to find the leftmost and the rightmost indices of the minimum and the maximum element from the array where arr[] consists of non-distinct elements.Examples: Input: arr[] = {2, 1, 1, 2, 1, 5, 6, 5} Output: Minimum left : 1 Minimum right : 4 Maximum left : 6 Maximum r
    15+ min read
  • Program to find the minimum (or maximum) element of an array
    Given an array, write functions to find the minimum and maximum elements in it. Examples: Input: arr[] = [1, 423, 6, 46, 34, 23, 13, 53, 4]Output: Minimum element of array: 1 Maximum element of array: 423 Input: arr[] = [2, 4, 6, 7, 9, 8, 3, 11]Output: Minimum element of array: 2 Maximum element of
    14 min read
  • Find the minimum and maximum sum of N-1 elements of the array
    Given an unsorted array A of size N, the task is to find the minimum and maximum values that can be calculated by adding exactly N-1 elements. Examples: Input: a[] = {13, 5, 11, 9, 7} Output: 32 40 Explanation: Minimum sum is 5 + 7 + 9 + 11 = 32 and maximum sum is 7 + 9 + 11 + 13 = 40.Input: a[] = {
    10 min read
  • Sum and Product of minimum and maximum element of an Array
    Given an array. The task is to find the sum and product of the maximum and minimum elements of the given array. Examples: Input : arr[] = {12, 1234, 45, 67, 1} Output : Sum = 1235 Product = 1234 Input : arr[] = {5, 3, 6, 8, 4, 1, 2, 9} Output : Sum = 10 Product = 9 Take two variables min and max to
    13 min read
  • Recursive Programs to find Minimum and Maximum elements of array
    Given an array of integers arr, the task is to find the minimum and maximum element of that array using recursion. Examples : Input: arr = {1, 4, 3, -5, -4, 8, 6}; Output: min = -5, max = 8 Input: arr = {1, 4, 45, 6, 10, -8}; Output: min = -8, max = 45 Recursive approach to find the Minimum element
    8 min read
  • Find the first, second and third minimum elements in an array
    Find the first, second and third minimum elements in an array in O(n). Examples: Input : 9 4 12 6 Output : First min = 4 Second min = 6 Third min = 9 Input : 4 9 1 32 12 Output : First min = 1 Second min = 4 Third min = 9 First approach : First we can use normal method that is sort the array and the
    8 min read
  • Minimize the maximum minimum difference after one removal from array
    Given an array arr[] of size n ? 3, the task is to find the minimum possible difference between the maximum and the minimum element from the array after removing one element. Examples: Input: arr[] = {1, 2, 3} Output: 1 Removing 1 will give 3 - 2 = 1 Removing 2, 3 - 1 = 2 And removing 3 will result
    11 min read
  • Find Array after removing -1 and closest non-negative left element
    Given an array arr[] of size N that contains -1 and all positive integers, the task is to modify the array and print the final array after performing the below valid operations: Choose -1 from the array.Remove the closest non-negative element (if there is any) to its left, as well as remove -1 itsel
    11 min read
  • Remove minimum elements from array so that max <= 2 * min
    Given an array arr, the task is to remove minimum number of elements such that after their removal, max(arr) <= 2 * min(arr). Examples: Input: arr[] = {4, 5, 3, 8, 3} Output: 1 Remove 8 from the array. Input: arr[] = {1, 2, 3, 4} Output: 1 Remove 1 from the array. Approach: Let us fix each value
    6 min read
  • Minimum element left from the array after performing given operations
    Given an array arr[] of N integers, the task is to remove the elements from both the ends of the array i.e. in a single operation, either the first or the last element can be removed from the current remaining elements of the array. This operation needs to be performed in such a way that the last el
    3 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