← Back to challenges

Lexicographically First and Last

JavaScriptHardstringssortingarrays

Instructions

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).
javascript
Loading editor…
⌘ ↵ to run
Walks through the solution with reasoning and edge cases.