  A theorem of Elekes and Szab\'o recognizes algebraic groups among certain
complex algebraic varieties with maximal size intersections with finite grids.
We establish a generalization to relations of any arity and dimension,
definable in: 1) stable structures with distal expansions (includes
algebraically and differentially closed fields of characteristic 0); and 2)
o-minimal expansions of groups. Our methods provide explicit bounds on the
power saving exponent in the non-group case. Ingredients of the proof include:
a higher arity generalization of the abelian group configuration theorem in
stable structures, along with a purely combinatorial variant characterizing
Latin hypercubes that arise from abelian groups; and Zarankiewicz-style bounds
for hypergraphs definable in distal structures.
