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
operations
to store the sequence of operations.Initialize an integer variable
targetIndex
to 0, which will keep track of the current index in thetarget
array.Inside the for loop:
Check if
targetIndex
is equal to the size of thetarget
array. If it is, there are no more elements to match in thetarget
array, so exit the loop by using abreak
statement.
Check if the current element in the
target
array at indextargetIndex
is equal toi
. If it is, it means the element at indextargetIndex
in thetarget
array matches the current valuei
in the range 1 ton
. In this case:Append "Push" to the
operations
vector to represent pushing the current valuei
onto the stack.Increment
targetIndex
to move to the next element in thetarget
array.
If the current element in the
target
array at indextargetIndex
is not equal toi
, it means that the element at indextargetIndex
in thetarget
array does not match the current valuei
in the range 1 ton
. In this case:Append "Push" to the
operations
vector to represent pushing the current valuei
onto the stack.Append "Pop" to the
operations
vector to represent popping an element from the stack.
Continue the loop until all elements in the
target
array have been matched or until the loop reaches the end of the range from 1 ton
.After the loop, return the
operations
vector, which contains the sequence of operations required to transform an array into thetarget
array using a stack.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)
Auxiliary Space Complexity:
O(n)
Code (C++)
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