Open In App

Find last remaining element after reducing the Array

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: 

Examples: 



Input: N = 5, arr[] = {1, 2, 3, 4, 5}, K = 7 
Output:
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:
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: 



Below is the implementation of the above approach:




// C++ program to find the value of the
// reduced Array by reducing the array
// based on the given conditions
 
#include <iostream>
using namespace std;
 
// Function to find the value of the
// reduced Array by reducing the array
// based on the given conditions
int find_value(int a[], int n, int k)
{
    // Variable to store the sum
    int sum = 0;
 
    // For loop to iterate through the
    // given array and find the sum
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
 
    // Return the required value
    return sum % k;
}
 
// Driver code
int main()
{
    int n = 5, k = 3;
    int a[] = { 12, 4, 13, 0, 5 };
    cout << find_value(a, n, k);
    return 0;
}




// Java program to find the value of the
// reduced Array by reducing the array
// based on the given conditions
 
public class GFG {
 
    // Function to find the value of the
    // reduced Array by reducing the array
    // based on the given conditions
    public static int find_value(int a[], int n, int k)
    {
        // Variable to store the sum
        int sum = 0;
 
        // For loop to iterate through the
        // given array and find the sum
        for (int i = 0; i < n; i++) {
            sum += a[i];
        }
 
        // Return the required value
        return sum % k;
    }
 
    // Driver code
    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 program to find the value of the
# reduced Array by reducing the array
# based on the given conditions
 
# Function to find the value of the
# reduced Array by reducing the array
# based on the given conditions
def find_value(a, n, k):
 
    # Variable to store the sum
    sum = 0
 
    # For loop to iterate through the
    # given array and find the sum
    for i in range(n):
        sum += a[i]
 
    # Return the required value
    return sum % k
 
# Driver code
if __name__ == "__main__":
    n, k = 5, 3;
    a = [12, 4, 13, 0, 5];
    print(find_value(a, n, k))




// C# program to find the value of the
// reduced Array by reducing the array
// based on the given conditions
using System;
 
class GFG {
 
    // Function to find the value of the
    // reduced Array by reducing the array
    // based on the given conditions
    public static int find_value(int []a, int n, int k)
    {
        // Variable to store the sum
        int sum = 0;
 
        // For loop to iterate through the
        // given array and find the sum
        for (int i = 0; i < n; i++) {
            sum += a[i];
        }
 
        // Return the required value
        return sum % k;
    }
 
    // Driver code
    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));
    }
}
 
// This code is contributed  by AnkitRai01




<script>
 
 
// Js program to find the value of the
// reduced Array by reducing the array
// based on the given conditions
 
// Function to find the value of the
// reduced Array by reducing the array
// based on the given conditions
function find_value( a, n, k)
{
    // Variable to store the sum
    let sum = 0;
 
    // For loop to iterate through the
    // given array and find the sum
    for (let i = 0; i < n; i++) {
        sum += a[i];
    }
 
    // Return the required value
    return sum % k;
}
 
// Driver code
let n = 5, k = 3;
    let a = [ 12, 4, 13, 0, 5 ];
document.write(find_value(a, n, k));
 
 
</script>

Output
1











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:

  1. Create a deque data structure (a double-ended queue) and  initialize it with the given array..
  2. 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.
  3. output the last remaining element in the deque.

Implementation:




#include <bits/stdc++.h>
using namespace std;
 
int findLastRemainingElement(int arr[], int N, int K) {
    deque<int> dq(arr, arr + N); // initialize deque using array
 
    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 program to find the value of the
// reduced Array by reducing the array
// based on the given conditions
 
import java.util.Deque;
import java.util.ArrayDeque;
 
public class Main {
 
    // Function to find the last remaining element in the array based on the given conditions
    public static int findLastRemainingElement(int[] arr, int N, int K) {
        // Initialize a deque using the input array
        Deque<Integer> dq = new ArrayDeque<>();
        for (int i = 0; i < N; i++) {
            dq.addLast(arr[i]);
        }
 
        while (dq.size() > 1) {
            // Take front and back elements from the deque and remove them
            int x = dq.removeFirst();
            int y = dq.removeLast();
 
            // Compute the sum of front and back elements and take modulo with K
            int z = (x + y) % K;
 
            // Push the result to the front of the deque
            dq.addFirst(z);
        }
 
        // Return the last remaining element in the deque
        return dq.getFirst();
    }
 
    // Driver code
    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 program to find the value of the
# reduced Array by reducing the array
# based on the given conditions
from collections import deque
 
def findLastRemainingElement(arr, N, K):
    # Initialize a deque using the input array
    dq = deque(arr)
     
    while len(dq) > 1:
        # Take front and back elements from the deque and remove them
        x = dq.popleft()
        y = dq.pop()
         
        # Compute the sum of front and back elements and take modulo with K
        z = (x + y) % K
         
        # Push the result to the front of the deque
        dq.appendleft(z)
     
    # Return the last remaining element in the deque
    return dq[0]
#Driver code
def main():
    N = 5
    K = 7
    arr = [1, 2, 3, 4, 5]
    result = findLastRemainingElement(arr, N, K)
    print(result)
 
if __name__ == "__main__":
    main()




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to find the last remaining element in the queue
    static int FindLastRemainingElement(int[] arr, int N, int K)
    {
        // Initialize a queue and populate it with the elements from the array
        Queue<int> dq = new Queue<int>(arr);
 
        // Continue the process until there is only one element left in the queue
        while (dq.Count > 1)
        {
            // Dequeue two elements from the front of the queue
            int x = dq.Dequeue();
            int y = dq.Dequeue();
 
            // Calculate the new element based on the sum of the dequeued elements modulo K
            int z = (x + y) % K;
 
            // Enqueue the result back into the queue
            dq.Enqueue(z);
        }
 
        // The last remaining element in the queue is the answer
        return dq.Dequeue();
    }
 
    static void Main(string[] args)
    {
        int N = 5, K = 7;
        int[] arr = { 1, 2, 3, 4, 5 };
 
        // Call the function to find and print the last remaining element
        Console.WriteLine(FindLastRemainingElement(arr, N, K));
    }
}




function findLastRemainingElement(arr, N, K) {
    let dq = arr.slice(); // Initialize a copy of the array
 
    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));

Output
1












Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(N), where N is the length of the array.


Article Tags :