Open In App

Find all possible original Arrays using given Difference Array and range of array elements

Last Updated : 21 Feb, 2022
Comments
Improve
Suggest changes
1 Like
Like
Report

Given an array arr[] of size N that contains the differences between the adjacents elements of an array. The task is to generate all possible arrays such that all the elements of the array lie in the range [L, R].

Examples:

Input: arr[] = {1, -3, 4}, L = 1, R = 6
Output: {3, 4, 1, 5}, {4, 5, 2, 6}
Explanation: These two are the only possible sequences having all the elements in given range.

Input: arr[] = {4}, L = 2, R = 5
Output: -1
Explanation: No such sequence is possible 

 

Approach: The solution is based on the concept of recursion. Use recursion in the range of L and R  and try all possible cases. If no such sequence is found print -1;

Below is the implementation of the above approach.

C++
// C++ program to implement the approach
#include <bits/stdc++.h>
using namespace std;

// Global variable to note
// if any sequence found or not
bool flag = false;

// Function to find a sequence
void find(int L, int R, int starting, vector<int>& arr,
          vector<int>& ans)
{
    if (starting == ans.size() - 1) {
        flag = true;
        for (auto elements : ans) {
            cout << elements << " ";
        }
        cout << "\n";
        return;
    }

    // Loop to form the sequence
    for (int i = L; i <= R; ++i) {
        if (starting == -1) {
            ans[starting + 1] = i;

            // Recursive call
            find(L, R, starting + 1, arr, ans);
        }
        else {

            // Check the previous
            if (i - ans[starting] == arr[starting]) {
                ans[starting + 1] = i;

                // Recursive call
                find(L, R, starting + 1, arr, ans);
            }
        }
    }
}

// Driver code
int main()
{
    vector<int> arr{ 1, -3, 4 };
    int L = 1;
    int R = 6;
    vector<int> ans(arr.size() + 1);
    find(L, R, -1, arr, ans);
    if (!flag)
        cout << (-1);

    return 0;
}

    // This code is contributed by rakeshsahni
Java Python3 C# JavaScript

 
 


Output
3 4 1 5 
4 5 2 6 


 

Time Complexity: O((L-R)*N)
Auxiliary Space: O(N)


 


Next Article
Article Tags :
Practice Tags :

Similar Reads