Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Last Updated :
25 Apr, 2023
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: 4
Explanation:
Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.
Operation 2: The array arr[] modifies to {-2 - 1, -1 + 2} = {-3, 1}.
Operation 3: The array arr[] modifies to {1 + 3} = {4}.
Therefore, the last remaining array element is 4.
Input: arr[] = {1, 8, 4}
Output: -11
Explanation:
Operation 1: The array arr[] modifies to {1 - 8, 4 - 8} = {7, -4}.
Operation 2: The array arr[] modifies to {-4 - 7 } = {-11}.
Therefore, the last remaining array element is -11.
Naive Approach: The simplest approach is to traverse the array until its size reduces to 1 and perform the given operations on the array. After completing the traversal, print the remaining elements. Below is the implementation of the above approach.
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to find the remaining array element
int findRemainingElement(vector<int>& arr) {
int n = arr.size();
while (n > 1) {
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i+1] - arr[i];
}
n--;
}
return arr[0];
}
// Driver code
int main() {
// Given input
vector<int> arr = {3, 4, 2, 1};
// Function call
int remainingElement = findRemainingElement(arr);
// Print the remaining element
cout << "Remaining element: " << remainingElement << endl;
return 0;
}
Java
import java.util.*;
public class Main {
// Function to find the remaining array element
public static int
findRemainingElement(List<Integer> arr)
{
int n = arr.size();
while (n > 1) {
for (int i = 0; i < n - 1; i++) {
arr.set(i, arr.get(i + 1) - arr.get(i));
}
n--;
}
return arr.get(0);
}
// Driver code
public static void main(String[] args)
{
// Given input
List<Integer> arr = Arrays.asList(3, 4, 2, 1);
// Function call
int remainingElement = findRemainingElement(arr);
// Print the remaining element
System.out.println("Remaining element: "
+ remainingElement);
}
}
// This code is contributed by user_dtewbxkn77n
Python3
# Python3 impelementation
def find_remaining_element(arr):
n = len(arr)
while n > 1:
for i in range(n - 1):
arr[i] = arr[i+1] - arr[i]
n -= 1
return arr[0]
# Driver code
arr = [3, 4, 2, 1]
# Function call
remaining_element = find_remaining_element(arr)
# Print the remaining element
print("Remaining element:", remaining_element)
# written by kk
C#
using System;
using System.Collections.Generic;
class MainClass {
// Function to find the remaining array element
static int FindRemainingElement(List<int> arr) {
int n = arr.Count;
while (n > 1) {
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i+1] - arr[i];
}
n--;
}
return arr[0];
}
// Driver code
static void Main() {
// Given input
List<int> arr = new List<int> {3, 4, 2, 1};
// Function call
int remainingElement = FindRemainingElement(arr);
// Print the remaining element
Console.WriteLine("Remaining element: " + remainingElement);
}
}
// This code is contributed by sarojmcy2e
JavaScript
function findRemainingElement(arr) {
let n = arr.length;
while (n > 1) {
for (let i = 0; i < n - 1; i++) {
arr[i] = arr[i+1] - arr[i];
}
n--;
}
return arr[0];
}
// Given input
let arr = [3, 4, 2, 1];
// Function call
let remainingElement = findRemainingElement(arr);
// Print the remaining element
console.log("Remaining element: " + remainingElement);
OutputRemaining element: 4
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
- Suppose the given array is arr[] = {a, b, c, d}. Then, performing the operations:
a, \ b, \ c, \ d\\ b-a, \ c-b, \ d-c\\ (c-b)-(b-a), \ (d-c)-(c-b) = c-2b+a, \ d-2c+b\\ -a+3b-3c+d
- Now, suppose the array arr[] = {a, b, c, d, e}. Then, performing the operations:
a, \ b, \ c, \ d, \ e\\ \vdots\\ a - 4b + 6c - 4d + e
- From the above two observations, it can be concluded that the answer is the sum of multiplication of coefficients of terms in the expansion of (x - y)(N - 1) and each array element arr[i].
- Therefore, the idea is to find the sum of the array arr[] after updating each array element as (arr[i]* (N - 1)C(i-1)* (-1)i).
Follow the steps below to solve the problem:
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 remaining
// array element after performing
// the given operations repeatedly
int lastElement(const int arr[], int n)
{
// Stores the resultant sum
int sum = 0;
int multiplier = n % 2 == 0 ? -1 : 1;
// Traverse the array
for (int i = 0; i < n; i++) {
// Increment sum by arr[i]
// * coefficient of i-th term
// in (x - y) ^ (N - 1)
sum += arr[i] * multiplier;
// Update multiplier
multiplier
= multiplier * (n - 1 - i)
/ (i + 1) * (-1);
}
// Return the resultant sum
return sum;
}
// Driver Code
int main()
{
int arr[] = { 3, 4, 2, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
cout << lastElement(arr, N);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Function to find the last remaining
// array element after performing
// the given operations repeatedly
public static int lastElement(int arr[], int n)
{
// Stores the resultant sum
int sum = 0;
int multiplier = n % 2 == 0 ? -1 : 1;
// Traverse the array
for (int i = 0; i < n; i++) {
// Increment sum by arr[i]
// * coefficient of i-th term
// in (x - y) ^ (N - 1)
sum += arr[i] * multiplier;
// Update multiplier
multiplier
= multiplier * (n - 1 - i) / (i + 1) * (-1);
}
// Return the resultant sum
return sum;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 3, 4, 2, 1 };
int N = 4;
System.out.println(lastElement(arr, N));
}
}
// This code is contributed by aditya7409.
Python3
# Python 3 program for the above approach
# Function to find the last remaining
# array element after performing
# the given operations repeatedly
def lastElement(arr, n):
# Stores the resultant sum
sum = 0
if n % 2 == 0:
multiplier = -1
else:
multiplier = 1
# Traverse the array
for i in range(n):
# Increment sum by arr[i]
# * coefficient of i-th term
# in (x - y) ^ (N - 1)
sum += arr[i] * multiplier
# Update multiplier
multiplier = multiplier * (n - 1 - i) / (i + 1) * (-1)
# Return the resultant sum
return sum
# Driver Code
if __name__ == '__main__':
arr = [3, 4, 2, 1]
N = len(arr)
print(int(lastElement(arr, N)))
# This code is contributed by SURENDRA_GANGWAR.
JavaScript
<script>
// JavaScript program for the above approach
// Function to find the last remaining
// array element after performing
// the given operations repeatedly
function lastElement(arr, n)
{
// Stores the resultant sum
let sum = 0;
let multiplier = n % 2 == 0 ? -1 : 1;
// Traverse the array
for (let i = 0; i < n; i++)
{
// Increment sum by arr[i]
// * coefficient of i-th term
// in (x - y) ^ (N - 1)
sum += arr[i] * multiplier;
// Update multiplier
multiplier
= multiplier * (n - 1 - i)
/ (i + 1) * (-1);
}
// Return the resultant sum
return sum;
}
// Driver Code
let arr = [ 3, 4, 2, 1 ];
let N = arr.length;
document.write(lastElement(arr, N));
// This code is contributed by Surbhi Tyagi.
</script>
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find the last remaining
// array element after performing
// the given operations repeatedly
public static int lastElement(int[] arr, int n)
{
// Stores the resultant sum
int sum = 0;
int multiplier = n % 2 == 0 ? -1 : 1;
// Traverse the array
for (int i = 0; i < n; i++) {
// Increment sum by arr[i]
// * coefficient of i-th term
// in (x - y) ^ (N - 1)
sum += arr[i] * multiplier;
// Update multiplier
multiplier
= multiplier * (n - 1 - i) / (i + 1) * (-1);
}
// Return the resultant sum
return sum;
}
// Driver code
static void Main()
{
int[] arr = { 3, 4, 2, 1 };
int N = 4;
Console.WriteLine(lastElement(arr, N));
}
}
// This code is contributed by susmitakundugoaldanga.
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read