From 8af0c7b85a63ddfddf836fc4a742310476973c61 Mon Sep 17 00:00:00 2001 From: Tatheer Fathima <148070120+T-Fathima@users.noreply.github.com> Date: Sat, 2 Nov 2024 16:58:28 +0000 Subject: [PATCH] added algo --- docs/Stack/Stack-permutation.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/Stack/Stack-permutation.md b/docs/Stack/Stack-permutation.md index 4e0762b49..a04a99632 100644 --- a/docs/Stack/Stack-permutation.md +++ b/docs/Stack/Stack-permutation.md @@ -101,3 +101,33 @@ int main() { ``` +### Python Implementation: +```python +def is_stack_permutation(input, output): + stack = [] + j = 0 + n = len(input) + + for i in range(n): + # Push the current element of the input array to the stack + stack.append(input[i]) + + # Check if the top of the stack matches the output array + while stack and stack[-1] == output[j]: + stack.pop() + j += 1 + + # If j has reached n, then output is a valid permutation + return j == n + +if __name__ == "__main__": + input = [1, 2, 3] + output = [2, 1, 3] + + if is_stack_permutation(input, output): + print("Yes, it is a stack permutation") + else: + print("No, it is not a stack permutation") +``` + +