Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.
We may make the following moves:
'U' moves our position up one row, if the position exists on the board;'D' moves our position down one row, if the position exists on the board;'L' moves our position left one column, if the position exists on the board;'R' moves our position right one column, if the position exists on the board;'!' adds the character board[r][c] at our current position (r, c) to the answer.(Here, the only positions that exist on the board are positions with letters on them.)
Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.
Example 1:
Input: target = "leet" Output: "DDR!UURRR!!DDD!"
Example 2:
Input: target = "code" Output: "RR!DDRR!UUL!R!"
Constraints:
1 <= target.length <= 100target consists only of English lowercase letters.Problem summary: On an alphabet board, we start at position (0, 0), corresponding to character board[0][0]. Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below. We may make the following moves: 'U' moves our position up one row, if the position exists on the board; 'D' moves our position down one row, if the position exists on the board; 'L' moves our position left one column, if the position exists on the board; 'R' moves our position right one column, if the position exists on the board; '!' adds the character board[r][c] at our current position (r, c) to the answer. (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map
"leet"
"code"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1138: Alphabet Board Path
class Solution {
public String alphabetBoardPath(String target) {
StringBuilder ans = new StringBuilder();
int i = 0, j = 0;
for (int k = 0; k < target.length(); ++k) {
int v = target.charAt(k) - 'a';
int x = v / 5, y = v % 5;
while (j > y) {
--j;
ans.append('L');
}
while (i > x) {
--i;
ans.append('U');
}
while (j < y) {
++j;
ans.append('R');
}
while (i < x) {
++i;
ans.append('D');
}
ans.append("!");
}
return ans.toString();
}
}
// Accepted solution for LeetCode #1138: Alphabet Board Path
func alphabetBoardPath(target string) string {
ans := []byte{}
var i, j int
for _, c := range target {
v := int(c - 'a')
x, y := v/5, v%5
for j > y {
j--
ans = append(ans, 'L')
}
for i > x {
i--
ans = append(ans, 'U')
}
for j < y {
j++
ans = append(ans, 'R')
}
for i < x {
i++
ans = append(ans, 'D')
}
ans = append(ans, '!')
}
return string(ans)
}
# Accepted solution for LeetCode #1138: Alphabet Board Path
class Solution:
def alphabetBoardPath(self, target: str) -> str:
i = j = 0
ans = []
for c in target:
v = ord(c) - ord("a")
x, y = v // 5, v % 5
while j > y:
j -= 1
ans.append("L")
while i > x:
i -= 1
ans.append("U")
while j < y:
j += 1
ans.append("R")
while i < x:
i += 1
ans.append("D")
ans.append("!")
return "".join(ans)
// Accepted solution for LeetCode #1138: Alphabet Board Path
struct Solution;
impl Solution {
fn alphabet_board_path(target: String) -> String {
let mut pos: Vec<(i32, i32)> = vec![];
for i in 0..5 {
for j in 0..5 {
pos.push((i, j));
}
}
pos.push((5, 0));
let mut v = vec!['a'];
for c in target.chars() {
v.push(c);
}
let n = v.len();
let mut res = "".to_string();
for i in 1..n {
let curr = pos[(v[i] as u8 - b'a') as usize];
let prev = pos[(v[i - 1] as u8 - b'a') as usize];
let mut r = curr.0 - prev.0;
let mut c = curr.1 - prev.1;
while r < 0 {
res.push('U');
r += 1;
}
while c < 0 {
res.push('L');
c += 1;
}
while r > 0 {
res.push('D');
r -= 1;
}
while c > 0 {
res.push('R');
c -= 1;
}
res.push('!');
}
res
}
}
#[test]
fn test() {
let target = "leet".to_string();
let res = "DDR!UURRR!!DDD!".to_string();
assert_eq!(Solution::alphabet_board_path(target), res);
let target = "code".to_string();
let res = "RR!DDRR!UUL!R!".to_string();
assert_eq!(Solution::alphabet_board_path(target), res);
}
// Accepted solution for LeetCode #1138: Alphabet Board Path
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1138: Alphabet Board Path
// class Solution {
// public String alphabetBoardPath(String target) {
// StringBuilder ans = new StringBuilder();
// int i = 0, j = 0;
// for (int k = 0; k < target.length(); ++k) {
// int v = target.charAt(k) - 'a';
// int x = v / 5, y = v % 5;
// while (j > y) {
// --j;
// ans.append('L');
// }
// while (i > x) {
// --i;
// ans.append('U');
// }
// while (j < y) {
// ++j;
// ans.append('R');
// }
// while (i < x) {
// ++i;
// ans.append('D');
// }
// ans.append("!");
// }
// return ans.toString();
// }
// }
Use this to step through a reusable interview workflow for this problem.
For each element, scan the rest of the array looking for a match. Two nested loops give n × (n−1)/2 comparisons = O(n²). No extra space since we only use loop indices.
One pass through the input, performing O(1) hash map lookups and insertions at each step. The hash map may store up to n entries in the worst case. This is the classic space-for-time tradeoff: O(n) extra memory eliminates an inner loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.