Probability a Wandering Knight Stays on the Board After K Moves

Last updated: November 29, 2026

Quick Overview

A chess knight starts on cell (r, c) of an n x n board and makes k moves, each chosen uniformly at random among its 8 possible moves (even ones that leave the board); return the probability it is still on the board after all k moves.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A chess knight starts on cell (r, c) of an n x n board and makes k moves, each chosen uniformly at random among its 8 possible moves (even ones that leave the board); return the probability it is still on the board after all k moves.

A Google onsite probability-DP problem that tests whether you set up a distribution over cells rather than enumerating 8^k paths. The interviewer also looks for clean handling of the fact that leaving the board is absorbing.

What the Interviewer Expects
  • Rejects the 8^k enumeration
  • Keeps a probability grid and pushes mass forward each step
  • Drops mass that leaves the board
  • Sums the grid after k steps
  • States O(k n^2) time and O(n^2) space
Key Topics to Cover
Dynamic Programming
Probability
Markov Chains
Rolling Arrays
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Return the expected number of moves before the knight first leaves the board, capped at k.
  • The board is very large and k is small; how do you avoid an n^2 grid?
  • Use backward DP so you can answer queries for many start cells at once.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: n, k, start (r, c).
  • Each move picks one of 8 knight offsets with probability 1/8.
  • Once off the board, the knight stays off.
  • Output: probability of being on the board after k moves...
High-Level Design

Let P_t[i][j] be the probability of standing on (i, j) after t moves without having left. P_0 has 1 at the start. To get P_{t+1}, each cell sends P_t[i][j] / 8 to each on-board knight destin...


Submit Your Answer
Markdown supported