DEV Community

jser
jser

Posted on • Updated on

BFE.dev #9. decode message

https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.

Alt Text

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 
Enter fullscreen mode Exit fullscreen mode

The way to collect the message is as follows

  1. start at top left
  2. move diagonally down right
  3. when cannot move any more, try to switch to diagonally up right
  4. when cannot move any more, try switch to diagonally down right, repeat 3
  5. 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
}
Enter fullscreen mode Exit fullscreen mode

I've posted above solution here

Passed!

Alt Text

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)