Check if Array elements can be made 0 by Subtracting left adjacent values
Last Updated :
31 Aug, 2022
Given an array A[] of size N, the task is to check if all the elements of the array, except 1st element can be made 0 by performing the following operation any number of times:
- For any index i, 0 < i < N, make A[i] = A[i] – A[i-1]
Print “YES” or “NO” accordingly.
Examples:
Input: N = 2, A[] = {2, 8, 4}
Output:YES.
Explanation: Choose i = 1, the array becomes {2, 6, 4}
Choose i = 1, the array becomes {2, 4, 4}
Choose i = 2, the array becomes {2, 4, 0}
Choose i = 1, the array becomes {2, 2, 0}
Choose i = 1, the array becomes {2, 0, 0}
Input: N = 2, A[] = {3, 4, 2}
Output: NO
Approach:
If first element of the array is a factor of all the remaining elements of the array, then the elements of array can be made 0, because any of them can be converted to have the value same as the first elements. Otherwise, it is not possible.
Follow the given the step to implement the given idea :
- Run a loop from i = 1 to N-1.
- Check if every element has a factor equal to the first element.
- If all the elements of the array have a factor equal to the first element the print YES.
- Otherwise, print NO.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool solve( int A[], int N)
{
bool flag = true ;
for ( int i = 1; i < N; i++) {
if (A[i] % A[0] != 0) {
flag = false ;
break ;
}
}
return flag;
}
int main()
{
int N = 3;
int A[] = { 2, 8, 4 };
if (solve(A, N))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static boolean solve( int [] A, int N)
{
boolean flag = true ;
for ( int i = 1 ; i < N; i++) {
if (A[i] % A[ 0 ] != 0 ) {
flag = false ;
break ;
}
}
return flag;
}
public static void main(String[] args)
{
int N = 3 ;
int A[] = { 2 , 8 , 4 };
if (solve(A, N)) {
System.out.print( "YES" );
}
else {
System.out.print( "NO" );
}
}
}
|
Python3
def solve(A, N):
flag = True
for i in range ( 1 ,N):
if (A[i] % A[ 0 ]! = 0 ):
flag = False ;
break
return flag
N = 3
A = [ 2 , 8 , 4 ]
if (solve(A, N)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
public class GFG {
static bool solve( int [] A, int N)
{
bool flag = true ;
for ( int i = 1; i < N; i++) {
if (A[i] % A[0] != 0) {
flag = false ;
break ;
}
}
return flag;
}
public static void Main( string [] args)
{
int N = 3;
int []A = { 2, 8, 4 };
if (solve(A, N)) {
Console.WriteLine( "YES" );
}
else {
Console.WriteLine( "NO" );
}
}
}
|
Javascript
function solve(A, N)
{
let flag = true ;
for (let i = 1; i < N; i++) {
if (A[i] % A[0] != 0) {
flag = false ;
break ;
}
}
return flag;
}
let N = 3;
let A = [2, 8, 4 ];
if (solve(A, N))
console.log( "YES" );
else
console.log( "NO" );
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...