Lexicographically First and Last

Published by Helen Yu in

Write a function that returns the lexicographically first and lexicographically last rearrangements of a lowercase string. Output the results in the following manner:

firstAndLast(string) ➞ [first, last]

Examples

firstAndLast("marmite") ➞ ["aeimmrt", "trmmiea"]

firstAndLast("bench") ➞ ["bcehn", "nhecb"]

firstAndLast("scoop") ➞ ["coops", "spooc"]

Notes

  • Lexicographically first: the permutation of the string that would appear first in the English dictionary (if the word existed).
  • Lexicographically last: the permutation of the string that would appear last in the English dictionary (if the word existed).
Watch a quick demo on how Edabit works.