Paths Between Numbers in a 3×3 Grid
Updated
Problem statement
The fixed grid is:
1 2 3
4 5 6
7 8 9Given distinct values startValue and targetValue, list the paths from the start to the target without visiting a cell more than once.
- Up, down, left, and right moves are always allowed.
- When
allowDiagonalis true, the four diagonal moves are also allowed. - When
shortestOnlyis true, return only paths with the minimum number of moves.
Write each path as its visited values joined by hyphens. Return all path strings in lexicographic order.
Function
enumerateGridPaths(startValue: int, targetValue: int, allowDiagonal: boolean, shortestOnly: boolean) → String[]Examples
Example 1
startValue = 1targetValue = 2allowDiagonal = falseshortestOnly = falsereturn = ["1-2","1-4-5-2","1-4-5-6-3-2","1-4-5-8-9-6-3-2","1-4-7-8-5-2","1-4-7-8-5-6-3-2","1-4-7-8-9-6-3-2","1-4-7-8-9-6-5-2"]These are all eight simple orthogonal paths from cell 1 to adjacent cell 2.
Example 2
startValue = 1targetValue = 9allowDiagonal = trueshortestOnly = truereturn = ["1-5-9"]Two diagonal moves through the center form the unique shortest path.
Example 3
startValue = 1targetValue = 3allowDiagonal = falseshortestOnly = truereturn = ["1-2-3"]The top-row route is the only two-move orthogonal path.
Constraints
1 <= startValue,targetValue <= 9.startValue != targetValue.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Word Ladder II: All Shortest TransformationsPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Word Ladder IIBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Course ScheduleAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Course ScheduleOracle · ONSITE INTERVIEWOracle interview questions
- Course SchedulePlaud · ONSITE INTERVIEW
- Explore an Unknown Grid and Find a PathLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Nearest Charging Station on a GridSpotify · ONSITE INTERVIEW
- Hierarchical Permission CheckeBay · ONSITE INTERVIEWeBay interview questions
- Evaluate DivisionPhonePe · ONSITE INTERVIEWPhonePe interview questions
- Count Friend CirclesOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions