Find last remaining element after reducing the Array
Last Updated :
03 Oct, 2023
Given an array arr[] of size N and an integer K. The task is to find the last remaining element in the array after reducing the array. The rules for reducing the array are:
- The first and last element say X and Y are chosen and removed from the array arr[].
- The values X and Y are added. Z = X + Y.
- Insert the value of Z % K into the array arr[] at the position ((N/2) + 1)th position, where N denotes the current length of the array.
Examples:
Input: N = 5, arr[] = {1, 2, 3, 4, 5}, K = 7
Output: 1
Explanation:
The given array arr[] reduces as follows:
{1, 2, 3, 4, 5} -> {2, 6, 3, 4}
{2, 6, 3, 4} -> {6, 6, 3}
{6, 6, 3} -> {2, 6}
{2, 6} -> {1}
The last element of A is 1.
Input: N = 5, arr[] = {2, 4, 7, 11, 3}, K = 12
Output: 3
Explanation:
The given array arr[] reduces as follows:
{2, 4, 7, 11, 3} -> {4, 5, 7, 11}
{4, 5, 7, 11} -> {5, 3, 7}
{5, 3, 7} -> {0, 3}
{0, 3} -> {3}
The last element of A is 3.
Naive approach: The naive approach for this problem is that at every step, find the first element and last element in the array and compute (X + Y) % K where X is the first element and Y is the last element of the array at every step. After computing this value, insert this value at the given position.
Time Complexity: O(N2)
Efficient Approach:
- On observing carefully, it can be said that the sum of the elements of the array modulo K is never changed in the array throughout.
- This is because we are basically inserting the value X + Y % K back into the array.
- Therefore, this problem can be solved in linear time by directly finding the sum of the array and finding the value sum % K.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int find_value( int a[], int n, int k)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
}
return sum % k;
}
int main()
{
int n = 5, k = 3;
int a[] = { 12, 4, 13, 0, 5 };
cout << find_value(a, n, k);
return 0;
}
|
Java
public class GFG {
public static int find_value( int a[], int n, int k)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
sum += a[i];
}
return sum % k;
}
public static void main(String[] args)
{
int n = 5 , k = 3 ;
int a[] = { 12 , 4 , 13 , 0 , 5 };
System.out.println(find_value(a, n, k));
}
}
|
Python3
def find_value(a, n, k):
sum = 0
for i in range (n):
sum + = a[i]
return sum % k
if __name__ = = "__main__" :
n, k = 5 , 3 ;
a = [ 12 , 4 , 13 , 0 , 5 ];
print (find_value(a, n, k))
|
C#
using System;
class GFG {
public static int find_value( int []a, int n, int k)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
}
return sum % k;
}
public static void Main( string [] args)
{
int n = 5, k = 3;
int []a = { 12, 4, 13, 0, 5 };
Console.WriteLine(find_value(a, n, k));
}
}
|
Javascript
<script>
function find_value( a, n, k)
{
let sum = 0;
for (let i = 0; i < n; i++) {
sum += a[i];
}
return sum % k;
}
let n = 5, k = 3;
let a = [ 12, 4, 13, 0, 5 ];
document.write(find_value(a, n, k));
</script>
|
Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Method 3:Using Deque
Explanation:
The idea here is to repeatedly remove the first and last elements of the deque, calculate the sum of these elements, and push the result to the front of the deque. This process is repeated until only one element is left in the deque, which is the answer to the problem.
By using a deque, we can efficiently remove elements from both ends of the container.
Approach:
- Create a deque data structure (a double-ended queue) and initialize it with the given array..
- While the size of the deque is greater than 1, perform the following steps:
a) Remove the first and last elements from the deque.
b) Compute the sum of these two elements modulo K, and add the result to the middle of the deque.
- output the last remaining element in the deque.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int findLastRemainingElement( int arr[], int N, int K) {
deque< int > dq(arr, arr + N);
while (dq.size() > 1) {
int x = dq.front();
int y = dq.back();
dq.pop_front();
dq.pop_back();
int z = x + y;
dq.push_front(z % K);
}
return dq.front();
}
int main() {
int N = 5, K = 7;
int arr[] = {1, 2, 3, 4, 5};
cout << findLastRemainingElement(arr, N, K) << endl;
return 0;
}
|
Java
import java.util.Deque;
import java.util.ArrayDeque;
public class Main {
public static int findLastRemainingElement( int [] arr, int N, int K) {
Deque<Integer> dq = new ArrayDeque<>();
for ( int i = 0 ; i < N; i++) {
dq.addLast(arr[i]);
}
while (dq.size() > 1 ) {
int x = dq.removeFirst();
int y = dq.removeLast();
int z = (x + y) % K;
dq.addFirst(z);
}
return dq.getFirst();
}
public static void main(String[] args) {
int N = 5 ;
int K = 7 ;
int [] arr = { 1 , 2 , 3 , 4 , 5 };
int result = findLastRemainingElement(arr, N, K);
System.out.println(result);
}
}
|
Python3
from collections import deque
def findLastRemainingElement(arr, N, K):
dq = deque(arr)
while len (dq) > 1 :
x = dq.popleft()
y = dq.pop()
z = (x + y) % K
dq.appendleft(z)
return dq[ 0 ]
def main():
N = 5
K = 7
arr = [ 1 , 2 , 3 , 4 , 5 ]
result = findLastRemainingElement(arr, N, K)
print (result)
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int FindLastRemainingElement( int [] arr, int N, int K)
{
Queue< int > dq = new Queue< int >(arr);
while (dq.Count > 1)
{
int x = dq.Dequeue();
int y = dq.Dequeue();
int z = (x + y) % K;
dq.Enqueue(z);
}
return dq.Dequeue();
}
static void Main( string [] args)
{
int N = 5, K = 7;
int [] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(FindLastRemainingElement(arr, N, K));
}
}
|
Javascript
function findLastRemainingElement(arr, N, K) {
let dq = arr.slice();
while (dq.length > 1) {
let x = dq.shift();
let y = dq.pop();
let z = x + y;
dq.unshift(z % K);
}
return dq[0];
}
const N = 5;
const K = 7;
const arr = [1, 2, 3, 4, 5];
console.log(findLastRemainingElement(arr, N, K));
|
Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(N), where N is the length of the array.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...