Reduce the instructions following the given conditions – GeeksforGeeks
Given an array dir_list that represents direction where the valid directions are “UP”, “Left”, “Right” and “Down”. Your goal is to reduce the instructions by eliminating those that contradict one another, or those consecutive instructions that are opposite to one another. If the list becomes empty, print -1.
Note: UP and Down are opposite to each other and Left and Right are also opposite to each other.
Input: dir_list = [“UP”, “Left”, “Right”, “Down”, “Right”, “UP”]
Output: [‘Right’, ‘UP’]
Explanation: Direction at index 1 and 2 cancel out each other. After their removal, dir_list become [“UP”, “Down”, “Right”, “UP”] Direction at index 0 and 1 also cancel out each other. After their removal, dir_list become [“Right”, “UP”]
Input: dir_list = [“UP”, “Down”]
Explanation: UP and Down are consecutively opposite to each other so, they are cancel out each other leaving an empty list.
Approach: This can be solved using a stack.
The idea is to eliminate the opposite directions by comparing top element of stack and last element of list.
Follow the below steps to implement the idea:
- First check if the List is empty or has only a single element, then, return the list itself.
- Create a stack, append the last element of the list to the stack, and pop it from the list.
- While the list is not empty
- If the stack is empty, pop the last element of the list and append it to the stack
- Set a = top element of the stack and pop the element and b = last element of the list and pop the element
- Check if a and b are not opposed to each other, append a and b into the stack respectively.
- After executing the loop, reverse the stack and return it.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(N)
Stay connected with us on social media platform for instant update click here to join our Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here
Denial of responsibility! FineRadar is an automatic aggregator around the global media. All the content are available free on Internet. We have just arranged it in one platform for educational purpose only. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials on our website, please contact us by email – [email protected]. The content will be deleted within 24 hours.