Given n integers in a maze indicating number of moves to be made from that position and a string which has “>” and “<" indicating which side to move. Starting position is first position. Print whether it stays inside the array or moves out of the array. Example:
Input : 3 2 1 1 > > < Output: It stays inside forever Explanation: It moves towards right by a position of 2, hence is at the last index, then it moves to the left by 1, and then it again moves to the right by 1. Hence it doesn't go out. Input: 2 1 2 > < Output: comes out Explanation: Starts at 0th index, moves right by 1 position, and then moves left by 2 to come out
Approach to the above problem is as follows:
We start from 0th index and move until we exceed n or decreased 0. If we reach at the same position twice then we are in an infinite loop and can never move out.
* use mark array to mark the visited positions
* start from 0th index and check the sign of move and move to that place marking that position as visited
* if visited we can never move out , hence break out
* check the reason of break from loop , and print the desired result.
// below is the python implementation of the above approach
Time complexity: O(n)
This article is contributed by Twinkl Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Possibility of a word from a given set of characters
- Count ways to place Knights moving in L shape in chessboard
- Count of all subsequences having adjacent elements with different parity
- Rearrange an array such that product of every two consecutive elements is a multiple of 4
- Largest sum contiguous subarray having only non-negative elements
- Maximize count of distinct elements possible in an Array from the given operation
- Check if two arrays can be made equal by reversing any subarray once
- Maximum distance between two points in coordinate plane using Rotating Caliper's Method
- Check if a string can be split into two strings with same number of K-frequent characters
- Sort a Bitonic Array
- Sort Array such that smallest is at 0th index and next smallest it at last index and so on
- Split array into K subsets to maximize their sum of maximums and minimums
- Count of substrings having all distinct characters
- Min steps to empty an Array by removing a pair each time with sum at most K
Improved By : vt_m