Skip to content

← Broadcasting step 4 of 6

Easy Primitives

What shape comes out

Jump to the task

Broadcasting lets elementwise operations combine compatible shapes. Compare dimensions from the right, padding the shorter shape with leading ones for the comparison.

For each pair of dimensions:

  1. If they are equal, keep that size.
  2. If one is one, use the other size.
  3. Otherwise, the shapes are incompatible.

For example:

(3, 1) and (4,)          (2, 3, 4) and (3, 1)

  (3, 1)                   (2, 3, 4)
  (1, 4)  padded           (1, 3, 1)  padded
  ------                   ---------
  (3, 4)                   (2, 3, 4)

Shapes (3, 4) and (3,) are incompatible: their last dimensions are four and three, and neither is one. (4, 4) and (4,) are compatible, but that does not tell you whether the calculation matches your intent. A vector aligns with the last axis; row weights may need an inserted axis.

Empty dimensions and scalars

The rule is not always to choose the larger size. Zero and one are compatible, and the output size is zero. For example, (0, 3) and (1, 3) broadcast to (0, 3), an empty result. Zero and two are incompatible.

An empty shape list [] represents a scalar, not an empty tensor. For broadcasting, its missing axes act like size-one axes, so it can combine with any valid tensor shape.

import torch

print(list(torch.broadcast_shapes((3, 1), (4,))))  # [3, 4]
print(list(torch.broadcast_shapes((0, 3), (1, 3))))  # [0, 3]
print(list(torch.broadcast_shapes((), (2, 2))))  # [2, 2]

This helper checks shapes without allocating tensors. In this exercise, implement the rules directly so you can trace why each pair succeeds or fails.

Your task

def broadcast_shape(a: list[int], b: list[int]) -> list[int] | None

Given two valid shapes with nonnegative integer dimensions, return their broadcasted shape as a list, or None if they are incompatible. Either list may be empty to represent a scalar. Do not construct tensors.

The starter simply returns the shape with more dimensions. It neither checks compatibility nor combines dimensions that need expansion.