03. Build an Array With Stack Operations
The problem can be found at the following link: Question Link
My Approach
Initialize an empty vector of strings named
operationsto store the sequence of operations.Initialize an integer variable
targetIndexto 0, which will keep track of the current index in thetargetarray.Inside the for loop:
Check if
targetIndexis equal to the size of thetargetarray. If it is, there are no more elements to match in thetargetarray, so exit the loop by using abreakstatement.
Check if the current element in the
targetarray at indextargetIndexis equal toi. If it is, it means the element at indextargetIndexin thetargetarray matches the current valueiin the range 1 ton. In this case:Append "Push" to the
operationsvector to represent pushing the current valueionto the stack.Increment
targetIndexto move to the next element in thetargetarray.
If the current element in the
targetarray at indextargetIndexis not equal toi, it means that the element at indextargetIndexin thetargetarray does not match the current valueiin the range 1 ton. In this case:Append "Push" to the
operationsvector to represent pushing the current valueionto the stack.Append "Pop" to the
operationsvector to represent popping an element from the stack.
Continue the loop until all elements in the
targetarray have been matched or until the loop reaches the end of the range from 1 ton.After the loop, return the
operationsvector, which contains the sequence of operations required to transform an array into thetargetarray using a stack.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(n)
Code (C++)
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
vector<string> operations;
int targetIndex = 0;
for (int i = 1; i <= n; i++) {
if (targetIndex == target.size()) {
break; // No more elements to match in the target array
}
if (target[targetIndex] == i) {
operations.push_back("Push");
targetIndex++;
} else {
operations.push_back("Push");
operations.push_back("Pop");
}
}
return operations;
}
};
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated
Was this helpful?