LeetCode problem #31 — Next Permutation (JavaScript)

Solution #1: Reverse-loop

LeetCode user ybmlk posted a wonderfully elegant solution, in which we loop through the numbers provided from end to start, looking for the first occurrence of a number decreasing, which will be our “left-swap”. Next we again look from right-to-left, until we find a number higher than our left-swap, and swap the two numbers round. This effectively gives us the lowest possible “swap” that can be achieved for the given array.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Duncan McArdle

Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.