GeeksforGeeks App
Open App
Browser
Continue

Check if given Array can be formed by increasing or decreasing element

Given an array arr[] of length N with N integers.  Assume all the elements of array arr[] are equal to 0 and start with the first element. The task is to obtain the given array after performing the given operations on it.  At last, you must be there from where you start. Return 1 if it is possible to obtain the array arr[] after some operations (possibly zero) else print 0.

• Increase the element at which you are by 1. Then move to the next element if exists.
• Decrease the element at which you are by 1. Then move to the previous element if exists.

Examples:

Input: arr[] = {1, -1, 0}
Output: 1
Explanation: First the array arr[] is ={0, 0, 0} and you are on the first index i.e., 0.
Move right by one, the element at index 0 is increased by 1 arr[] = {1, 0, 0}, Now, you are on index 1.
Move left by one, the element at index 1 is decreased by 1 arr[] = {1, -1, 0}, Now, you are on index 0.
The array arr[] can be achieved by a finite number of operations i.e., 2, So, print 1.

Input: arr[] = {3, -1, -2, 0}
Output: 1

Approach

The basic idea is to eliminate all the consecutive zeroes from the end of the array till we get a non-zero element and then perform the given operations.

Follow the below steps to solve the problem:

• Initialize a variable prev = 0 and n = size of vector v.
• Remove all the consecutive zeros from back till we get a non-zero element.
• If the vector is empty it means all the elements were zeros so return 1.
• If there is only one element left in the array
• If the first element is less than equal to 0 or
• If the last element is greater than 0, then return 0.
• Else run a loop from n-1 to 1 index of the array and subtract v[i] from Prev.
• If Prev is less than or equal to 0 at any point of time then return 0.
• After executing the loop if Prev = v[0] then return 1, else return 0.

Below is the implementation of the above approach:

C++

 `// C++ code to implement the above approach` `#include ``#define ll long long``using` `namespace` `std;` `// Function to find is it possible to make``// the array or not` `bool` `solve(vector<``int``> v)``{` `    ``ll prev = 0, n = v.size();` `    ``// Remove all the consecutive zeros from back``    ``// till we get a non-zero element` `    ``while` `(!v.empty() && v.back() == 0) {``        ``v.pop_back();``    ``}` `    ``// All the elements were zeros so return 1` `    ``if` `(v.empty()) {``        ``return` `1;``    ``}` `    ``// If there is only one element left in the array``    ``// or the first element is less than equal to 0``    ``// or the last element is greater than 0 then return 0` `    ``if` `(v.size() == 1 || v[0] <= 0 || v.back() > 0) {``        ``return` `0;``    ``}` `    ``for` `(ll i = v.size() - 1; i > 0; i--) {``        ``prev = prev - v[i];` `        ``if` `(prev <= 0)``            ``return` `0;``    ``}` `    ``if` `(prev == v[0])``        ``return` `1;` `    ``return` `0;``}` `// Driver Code` `int` `main()``{` `    ``vector<``int``> vec = { 1, -1, 0 };``    ``cout << solve(vec) << endl;` `    ``vector<``int``> vec2 = { 3, -1, -2, 0 };``    ``cout << solve(vec2) << endl;` `    ``vector<``int``> vec3 = { 1, 1, 1, 0 };``    ``cout << solve(vec3) << endl;` `    ``return` `0;``}`

Java

 `// Java code to implement the above approach` `import` `java.io.*;``import` `java.util.*;` `class` `GFG {` `  ``static` `int` `solve(Vector v)``  ``{``    ``long` `prev = ``0``;``    ``long` `n = v.size();` `    ``// Remove all the consecutive zeros from back``    ``// till we get a non-zero element``    ``while` `(!v.isEmpty() && v.lastElement() == ``0``) {``      ``v.remove(v.size() - ``1``);``    ``}` `    ``// All the elements were zeros so return 1``    ``if` `(v.isEmpty()) {``      ``return` `1``;``    ``}` `    ``// If there is only one element left in the array``    ``// or the first element is less than equal to 0``    ``// or the last element is greater than 0 then return``    ``// 0``    ``if` `(v.size() == ``1` `|| v.get(``0``) <= ``0``        ``|| v.lastElement() > ``0``) {``      ``return` `0``;``    ``}` `    ``for` `(``int` `i = (``int``)(v.size() - ``1``); i > ``0``; i--) {``      ``prev = prev - v.get(i);` `      ``if` `(prev <= ``0``)``        ``return` `0``;``    ``}` `    ``if` `(prev == v.get(``0``))``      ``return` `1``;` `    ``return` `0``;``  ``}` `  ``public` `static` `void` `main(String[] args)``  ``{``    ``Vector vec = ``new` `Vector<>();``    ``vec.add(``1``);``    ``vec.add(-``1``);``    ``vec.add(``0``);``    ``System.out.println(solve(vec));` `    ``Vector vec2 = ``new` `Vector<>();``    ``vec2.add(``3``);``    ``vec2.add(-``1``);``    ``vec2.add(-``2``);``    ``vec2.add(``0``);``    ``System.out.println(solve(vec2));` `    ``Vector vec3 = ``new` `Vector<>();``    ``vec3.add(``1``);``    ``vec3.add(``1``);``    ``vec3.add(``1``);``    ``vec3.add(``0``);``    ``System.out.println(solve(vec3));``  ``}``}` `// This code is contributed by lokesh.`

Python3

 `# Python code to implement the above approach` `# Function to find is it possible to make``# the array or not` `def` `solve(v):``    ``prev ``=` `0``;``    ``n ``=` `len``(v);` `    ``# Remove all the consecutive zeros from back``    ``# till we get a non-zero element` `    ``while` `(``len``(v)>``0` `and` `v[``len``(v)``-``1``] ``=``=` `0``):``        ``v.pop();` `    ``# All the elements were zeros so return 1` `    ``if` `(``len``(v)``=``=``0``) :``        ``return` `1``;` `    ``# If there is only one element left in the array``    ``# or the first element is less than equal to 0``    ``# or the last element is greater than 0 then return 0` `    ``if` `(``len``(v) ``=``=` `1` `or` `v[``0``] <``=` `0` `or` `v[``len``(v)``-``1``] > ``0``) :``        ``return` `0``;` `    ``for` `i ``in` `range` `(``len``(v) ``-` `1``, ``0``, ``-``1``) :``        ``prev ``=` `prev ``-` `v[i];` `        ``if` `(prev <``=` `0``):``            ``return` `0``;``    ` `    ``if` `(prev ``=``=` `v[``0``]):``        ``return` `1``;` `    ``return` `0``;`  `# Driver Code``vec ``=` `[ ``1``, ``-``1``, ``0``];``print``(solve(vec));` `vec2 ``=` `[ ``3``, ``-``1``, ``-``2``, ``0``];``print``(solve(vec2));` `vec3 ``=` `[ ``1``, ``1``, ``1``, ``0``];``print``(solve(vec3));`

Javascript

 `// Javascript code to implement the above approach` `// Function to find is it possible to make``// the array or not` `function` `solve(v)``{` `    ``let prev = 0, n = v.length` `    ``// Remove all the consecutive zeros from back``    ``// till we get a non-zero element` `    ``while` `(v.length!=0 && v[v.length-1] == 0) {``        ``v.pop()``    ``}` `    ``// All the elements were zeros so return 1` `    ``if` `(v.length==0) {``        ``return` `1``    ``}` `    ``// If there is only one element left in the array``    ``// or the first element is less than equal to 0``    ``// or the last element is greater than 0 then return 0` `    ``if` `(v.length == 1 || v[0] <= 0 || v[v.length-1] > 0) {``        ``return` `0``    ``}` `    ``for` `(let i = v.length - 1; i > 0; i--) {``        ``prev = prev - v[i]` `        ``if` `(prev <= 0)``            ``return` `0``    ``}` `    ``if` `(prev == v[0])``        ``return` `1` `    ``return` `0``}`  `    ``let vec = [1, -1, 0]``    ``console.log(solve(vec))` `    ``let vec2 = [3, -1, -2, 0 ]``    ``console.log(solve(vec2))` `    ``let vec3 = [1, 1, 1, 0 ]``    ``console.log(solve(vec3))` `// This code is contributed by poojaagarwal2.`

C#

 `// C# code to implement the above approach` `using` `System;``using` `System.Linq;``using` `System.Collections.Generic;` `class` `GFG``{``    ``static` `int` `Solve(List<``int``> v)``    ``{``        ``long` `prev = 0;``        ``long` `n = v.Count;` `        ``// Remove all the consecutive zeros from back``        ``// till we get a non-zero element``        ``while` `(v.Count > 0 && v.Last() == 0)``        ``{``            ``v.RemoveAt(v.Count - 1);``        ``}` `        ``// All the elements were zeros so return 1``        ``if` `(v.Count == 0)``        ``{``            ``return` `1;``        ``}` `        ``// If there is only one element left in the array``        ``// or the first element is less than equal to 0``        ``// or the last element is greater than 0 then return``        ``// 0``        ``if` `(v.Count == 1 || v[0] <= 0``            ``|| v.Last() > 0)``        ``{``            ``return` `0;``        ``}` `        ``for` `(``int` `i = v.Count - 1; i > 0; i--)``        ``{``            ``prev = prev - v[i];` `            ``if` `(prev <= 0)``                ``return` `0;``        ``}` `        ``if` `(prev == v[0])``            ``return` `1;` `        ``return` `0;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``List<``int``> vec = ``new` `List<``int``> { 1, -1, 0 };``        ``Console.WriteLine(Solve(vec));` `        ``List<``int``> vec2 = ``new` `List<``int``> { 3, -1, -2, 0 };``        ``Console.WriteLine(Solve(vec2));` `        ``List<``int``> vec3 = ``new` `List<``int``> { 1, 1, 1, 0 };``        ``Console.WriteLine(Solve(vec3));``    ``}``}`

Output

```1
1
0```

Time Complexity: O(N)
Auxiliary Space: O(1)

Related Articles:

My Personal Notes arrow_drop_up
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://www.geeksforgeeks.org/check-if-given-array-can-be-formed-by-increasing-or-decreasing-element/?type=article&id=918552", "fetch_time": 1686174999000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2023-23/segments/1685224654016.91/warc/CC-MAIN-20230607211505-20230608001505-00172.warc.gz", "warc_record_offset": 834704704, "warc_record_length": 39709, "token_count": 3402, "char_count": 9308, "score": 3.8125, "int_score": 4, "crawl": "CC-MAIN-2023-23", "snapshot_type": "latest", "language": "en", "language_score": 0.8773909211158752, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00038-of-00064.parquet"}