Skip to content

ORIGINAL CODING QUESTION

Spread-out speaker order

Panel speakers are numbered 1 to n by seniority. A running order lists every speaker exactly once. To avoid back-to-back speakers of similar seniority, any two speakers who appear next to each other must have numbers that differ by at least d. Count the valid running orders.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

Two integers n d. Print the number of valid orders.

Constraints

1 ≤ n ≤ 9; 1 ≤ d ≤ 9. A single speaker always forms one valid order.

Example 1

Input

4 2

Output

2

Only 2 4 1 3 and 3 1 4 2 keep every neighbouring pair at least 2 apart.

Example 2

Input

3 2

Output

0

Speaker 2 differs from both other speakers by 1, so no order works.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Place speakers left to right and track which numbers are already used.

Hint 2

A candidate may be placed only if it is unused and far enough from the previously placed speaker.

Hint 3

Undo the used mark after each recursive call so the next candidate sees the original state.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →