VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-stops-given-path/

⇱ Minimum number of stops from given path - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of stops from given path

Last Updated : 2 Mar, 2023

There are many points in two-dimensional space which need to be visited in a specific sequence. Path from one point to other is always chosen as shortest path and path segments are always aligned with grid lines. Now we are given the path which is chosen for visiting the points, we need to tell the minimum number of points that must be needed to generate given path. Examples:

In above diagram, we can see that there 
must be at least 3 points to get above 
path, which are denoted by A, B and C

We can solve this problem by observing the pattern of movement when visiting the stops. If we want to take the shortest path from one point to another point then we will move in either one or max two directions i.e. it is always possible to reach the other point following maximum two directions and if more than two directions are used then that path won’t be shortest, for example, path LLURD can be replaced with LLL only, so to find minimum number of stops in the path, we will loop over the characters of the path and maintain a map of directions taken till now. 

If at any index we found both β€˜L’ as well as β€˜R’ or we found both β€˜U’ as well as β€˜D’ then there must be a stop at current index, so we will increase the stop count by one and we will clear the map for next segment. Total time complexity of the solution will be O(N) 

Implementation:


Output
3

Time Complexity: O(n*logn).
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: