Problem Β· Combinatorics

The Three Knights 🎠

Learn this problem
● HardTiktokINTERNOA
See Tiktok hiring insights

Problem statement

Given a grid with n rows and m columns, count the possible placements of three knights such that no two knights attack each other. No two knights may occupy the same cell.

A knight at (a1, b1) attacks (a2, b2) when either:

  • |a1 - a2| = 1 and |b1 - b2| = 2, or
  • |a1 - a2| = 2 and |b1 - b2| = 1.

Return the number of unordered three-cell placements in which no pair of cells is a knight's move apart.

Function

countPlacements(n: int, m: int) β†’ long

Examples

Example 1

n = 2m = 3return = 12

There are 20 ways to choose three of the six cells. The board has two attacking cell pairs, and each pair appears with four possible third cells. Therefore 20 - 2 * 4 = 12 placements are valid.

Constraints

  • 1 <= n
  • 1 <= m
  • n * m <= 10^6

More Tiktok problems

drafts saved locally
public long countPlacements(int n, int m) {
    // write your code here
}
n2
m3
expected12
checking account