Problem · String

Robot Final Direction

Learn this problem
EasyAirbnbNEW GRADOA

Problem statement

A robot starts at position 0 on a horizontal line and follows a string commands containing only L and R.

  • Each L moves the robot one step to the left.
  • Each R moves the robot one step to the right.

After every command has been executed in order, return:

  • "L" if the robot stops to the left of its starting position.
  • An empty string if the robot stops at its starting position.
  • "R" if the robot stops to the right of its starting position.

A solution with time complexity no worse than O(commands.length^2) fits within the execution time limit.

Function

robotDirection(commands: String) → String

Examples

Example 1

commands = "RLLRLL"return = "L"

The first two commands and the next two commands each return the robot to its starting position. The final two L commands leave it two steps to the left, so the result is "L".

Example 2

commands = "LLRLLLRRRR"return = ""

The string contains five L commands and five R commands, so the robot returns to its starting position and the result is an empty string.

Example 3

commands = "RRL"return = "R"

Two right moves and one left move leave the robot one step to the right, so the result is "R".

More Airbnb problems

drafts saved locally
public String robotDirection(String commands) {
    // write your code here
}
commands"RLLRLL"
expected"L"
checking account