Improved inner dimensions algorithm.