https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.
This article is about the coding problem BFE.dev#9. decode message
Problem
Your are given a 2-D array of characters. There is a hidden message in it.
I B C A L K A
D R F C A E A
G H O E L A D
The way to collect the message is as follows
- start at top left
- move diagonally down right
- when cannot move any more, try to switch to diagonally up right
- when cannot move any more, try switch to diagonally down right, repeat 3
- stop when cannot neither move down right or up right. the
character on the path is the message
for the input above, IROCLED
should be returned.
Analysis
While moving forward, the direction only changes along the y-axis, meaning we could use a flag to hold the vertical direction.
By keep tracking current position x, y
, we could get the next position x + 1, y + 1
, or x + 1, y - 1
.
When border is met, we change the vertical direction. When the last element is traversed, stop and return the result.
Let's write some code
The code is fairly simple.
/**
* @param { string[][] } message
* @returns { string }
*/
function decode(message) {
// edge case
const rows = message.length
if (rows === 0) return ''
const cols = message[0].length
if (cols === 0) return ''
let result = ''
let i = 0
let j = 0
// keep track of the direction vertically
let directionY = 1
while (j < cols) {
result += message[i][j]
// switch direction at the border
if (i === rows - 1) {
directionY = -1
}
if (i === 0) {
directionY = 1
}
i += directionY
j += 1
}
return result
}
I've posted above solution here
Passed!
If you are interested, have a try at BFE.dev https://bigfrontend.dev/problem/decode-message
Hope it helps, see you next time!
Top comments (0)