← All challenges

Next Permutation

Array & Sequence ★★★☆

Given an arrangement of 8 distinct integers, return the next lexicographic permutation.

A1:H1 holds 8 distinct integers in some arrangement — think of them as the seeding for an 8-team bracket. You want the next seeding in lexicographic order, so the output is also a row of 8 distinct integers (the same multiset, permuted).

If the current arrangement is the largest possible (strictly decreasing), the “next” wraps back to the smallest (strictly increasing) — but the input here is not the maximum, so wrap-around won’t trigger.

There are 8! = 40,320 arrangements. The classic algorithm walks right-to-left to find the rightmost ascending pair, swaps the pivot with the smallest larger element to its right, then reverses the suffix.

Input

Range A1:H1

ABCDEFGH
1 35876421
Hint

Scan right-to-left for the first position where the value is smaller than its right neighbour — that's the pivot. Swap the pivot with the smallest value to its right that's still larger than the pivot, then reverse everything to the right of the pivot.

Solution
=LET(
  combo, A1:H1,
  cols, COLUMNS(combo),
  rev, LAMBDA(arr, LET(r,COLUMNS(arr), INDEX(arr,SEQUENCE(1,r,r,-1)))),
  small_neighbor, LAMBDA(me, arr,
    IF(COLUMNS(arr)=1, 0,
      LET(last_two, TAKE(arr,,-2),
        IF(TAKE(last_two,,1) < TAKE(last_two,,-1),
          TAKE(last_two,,1),
          me(me, DROP(arr,,-1))
        )
      )
    )
  ),
  pivot, small_neighbor(small_neighbor, combo),
  tmp, TAKE(combo,, XMATCH(pivot,combo)-cols),
  small_right, MINIFS(tmp, tmp, ">"&pivot),
  smalls, HSTACK(pivot, small_right),
  swap, IF(ISNUMBER(XMATCH(combo,smalls)), combo*-1+SUM(smalls), combo),
  IF(pivot=0,
    rev(combo),
    HSTACK(TAKE(swap,,XMATCH(pivot,combo)), rev(TAKE(swap,,XMATCH(pivot,combo)-cols)))
  )
)