Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Turtle Navigation on Grid

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Turtle Navigation on Grid. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Wix Studio can model editor interactions on a bounded square grid. Given an N x N grid, a starting cell, an initial facing direction, and a command sequence, compute the final position and facing direction.

Commands have the following meanings:

  • F: Move forward one cell. If the next cell is outside the grid, remain in the current cell.
  • L: Turn 90 degrees left without changing position.
  • R: Turn 90 degrees right without changing position.

Use zero-based coordinates, where (0, 0) is the northwest corner. Directions are represented by N, E, S, and W.

Formal Specification

Implement final_position(n, start, direction, commands):

  • n is an integer grid size.
  • start is a two-element list [row, column].
  • direction is one of N, E, S, or W.
  • commands is a string containing only F, L, and R.
  • Return a dictionary with keys row, col, and direction.

Constraints

  • 1 <= n <= 10^6
  • 0 <= start[0], start[1] < n
  • 0 <= len(commands) <= 10^7
  • The input contains only valid directions and commands.
  • The grid does not wrap around.

Function Signature

def final_position(n, start, direction, commands):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output