Vacuum Cleaner Route
1 min read

Vacuum Cleaner Route

Given a string representing the sequence of moves a robot vacuum makes, return whether or not it will return to its original position. The string will only contain L, R, U, and D characters, representing left, right, up, and down respectively.

Ex: Given the following strings...

"LR", return true
"URURD", return false
"RUULLDRD", return true

This problem can be solved in following steps :-

  1. Create two variables UD and LR with initial value Zero representing Up-Down and Left-Right respectively.
  2. Traverse the String indices.
  3. If character is ‘L’, then increase value of variable LR by 1 and if character is ‘R’, then decrease the value of variable LR by 1.
  4. If character is ‘U’, then increase value of variable UD by 1 and if character is ‘D’, then decrease the value of variable UD by 1.
  5. If value of both LR and UD is zero, then return true, otherwise return false.
fun main() {
    val route = "LRLR"
   
    print(returnToPosition(route))
}

fun returnToPosition(route: String): Boolean {
   var UD = 0
   var LR = 0
    
   for(i in route.indices) {
       if(route[i] == 'L'){
           LR++
       } else if (route[i] == 'R') {
           LR--
       } else  if(route[i] == 'U'){
           UD++
       } else if (route[i] == 'D') {
           UD--
       }
   } 
   return LR == 0 && UD == 0
}

Enjoying these posts? Subscribe for more