Box ‘o Numbers

Arrange the numbers 1 to 8 in the grid below such that adjacent numbers are not in adjacent boxes (horizontally, vertically, or diagonally):

       ___
| 1 |
=============
| 6 | 4 | 3 |
=============
| 2 | 7 | 5 |
=============
| 8 |
=====

The arrangement above, for example, is wrong because 3 & 4, 4 & 5, 6 & 7, and 7 & 8 are adjacent.

Solution

The key is putting the 1 & 8 in the center spots – which is required, because those spots both border all but one of the other spots, and 1 & 8 are the only numbers that are only adjacent to one number.

From there, the 2 & 7 are forced, then you have your choice of the next number, which then forces the rest. Really, though there are only two valid solutions, and they are mirror images of each other.

💡Strategies for Solving This Problem

Array Processing Problem

Without seeing the exact problem, this is likely about processing arrays of numbers with specific operations. Common themes: find patterns, calculate sums/products, or determine properties.

Common "Box of Numbers" Problems

1. Find missing/duplicate: Covered elsewhere

2. Maximum subarray sum: Kadane's algorithm

3. Product of array except self: Prefix/suffix products

4. Find equilibrium: Left sum = right sum

Maximum Subarray (Kadane's)

Find contiguous subarray with largest sum.

Key insight: At each position, decide whether to extend current subarray or start new one.

maxEndingHere = max(nums[i], maxEndingHere + nums[i])

O(n) time, O(1) space. Classic DP problem.

Product Except Self

Return array where output[i] is product of all elements except nums[i].

Can't use division (what if there's a zero?). Use prefix and suffix products.

O(n) time, O(1) space (using output array doesn't count).

Equilibrium Index

Find index where sum of left elements equals sum of right elements.

Calculate total sum, then iterate tracking left sum. When leftSum == totalSum - leftSum - nums[i], found it.

O(n) time, O(1) space.

Scroll to Top