diff --git a/Algorithms_and_Data_Structures/Stack/Stack_permutation.py b/Algorithms_and_Data_Structures/Stack/Stack_permutation.py new file mode 100644 index 0000000000..39d3393fb0 --- /dev/null +++ b/Algorithms_and_Data_Structures/Stack/Stack_permutation.py @@ -0,0 +1,21 @@ +def is_stack_permutation(input, output): + stack = [] # Use list as a stack + j = 0 # Pointer for the output sequence + for i in range(len(input)): + # Push the current element of the input array onto 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 # Move to the next element in output + # If j has reached the length of output, then output is a valid permutation + return j == len(output) + +# Example usage +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") diff --git a/Project-Structure.md b/Project-Structure.md index ce7a39529b..e37926277b 100644 --- a/Project-Structure.md +++ b/Project-Structure.md @@ -148,6 +148,7 @@ * [Postfixtoprefix](Algorithms_and_Data_Structures/Stack/PostfixToPrefix.py) * [Prefixtoinfix](Algorithms_and_Data_Structures/Stack/PrefixToInfix.py) * [Prefixtopostfix](Algorithms_and_Data_Structures/Stack/PrefixToPostfix.py) + * [Stack Permutation](Algorithms_and_Data_Structures/Stack/Stack_permutation.py) * [Stack](Algorithms_and_Data_Structures/Stack/stack.py) * Strings * [Longest Palindromic Substring](Algorithms_and_Data_Structures/Strings/longest_palindromic_substring.py)