LeetCode Entry

2125. Number of Laser Beams in a Bank

3.01.2024 medium 2024 kotlin

Beams count between consequent non-empty row's 1s.

2125. Number of Laser Beams in a Bank medium blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/460

Problem TLDR

Beams count between consequent non-empty row’s 1s.

Intuition

By the problem definition, count = sum_i_j(count_i * count_j)

Approach

Let’s use some Kotlin’s API:

  • map
  • filter
  • windowed
  • sum

Complexity

  • Time complexity: \(O(nm)\)

  • Space complexity: \(O(n)\), can be reduced to O(1) with asSequence and fold.

Code


  fun numberOfBeams(bank: Array<String>) =
    bank.map { it.count { it == '1' } }
      .filter { it > 0 }
      .windowed(2)
      .map { (a, b) -> a * b }
      .sum() ?: 0