Find the direction from given string

Easy
0/40
0 upvote
Asked in company
Microsoft

Problem statement

You are given a string str consisting only of the characters 'L' and 'R'. Imagine a pivot on a compass that is initially pointing North (N).

Your task is to determine the final direction of the pivot after performing a series of rotations as described by the input string.

  • 'L' represents a 90-degree left (counter-clockwise) rotation.


  • 'R' represents a 90-degree right (clockwise) rotation.


  • Detailed explanation ( Input/output format, Notes, Images )
    Input Format:
    A single line containing the string str.
    


    Output Format:
    Print a single character representing the final direction: 'N' for North, 'E' for East, 'S' for South, or 'W' for West.
    


    Note:
    The compass directions follow a cycle: North -> East -> South -> West -> North.
    
    This problem can be efficiently solved by mapping the directions to numbers (e.g., N=0, E=1, S=2, W=3) and using modular arithmetic to track the current state.
    
    Sample Input 1:
    LLRLRRL
    


    Sample Output 1:
    W
    


    Explanation for Sample 1:
    - Initial direction: N
    - L: -> W
    - L: -> S
    - R: -> W
    - L: -> S
    - R: -> W
    - R: -> N
    - L: -> W
    The final direction is West (W).
    


    Sample Input 2:
    R
    


    Sample Output 2:
    E
    


    Explanation for Sample 2:
    - Initial direction: N
    - R: -> E
    The final direction is East (E).
    


    Expected Time Complexity:
    The expected time complexity is O(N), where N is the length of the string.
    


    Constraints:
    0 <= N <= 10^5
    `str` contains only 'L' and 'R'.
    
    Time limit: 1 sec
    
    Approaches (1)
    Find the direction from given string
    Time Complexity
    Space Complexity
    Code Solution
    (100% EXP penalty)
    Find the direction from given string
    Full screen
    Console