Build an Array With Stack Operations

Given an array target and an integer n. In each iteration, you will read a number from  list = {1,2,3..., n}.

Build the target array using the following operations:

  • Push: Read a new element from the beginning list, and push it in the array.
  • Pop: delete the last element of the array.
  • If the target array is already built, stop reading more elements.

Return the operations to build the target array. You are guaranteed that the answer is unique.

Example :

Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: 
Read number 1 and automatically push in the array -> [1]
Read number 2 and automatically push in the array then Pop it -> [1]
Read number 3 and automatically push in the array -> [1,3]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<stringbuildArray(vector<int&targetint n)
{
    vector<stringres;
    int max1 = target[target.size() - 1];
    for (int i = 1i <= min(max1n); i++)
    {
        int j = 0;
        for (j = 0j < target.size(); j++)
            if (target[j] == i)
            {
                res.push_back("Push");
                break;
            }
        if (j == target.size())
        {
            res.push_back("Push");
            res.push_back("Pop");
        }
    }
    return res;
}

int main()
{
    vector<inttarget = {13};
    int n = 3;

    vector<stringres = buildArray(targetn);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment