DEV Community

JP Antunes
JP Antunes

Posted on

1 1

Next Permutation

Today's Leetcode problem is quite interesting and, personally, I found the in-line array mutation tricky to get right.

We are asked to return the next highest number possible with a given array, falling back to sorting it by ascending order if the source value is the highest possible for that set of numbers.

Sound like a couple of loops to me!

var nextPermutation = function(nums) {
  for (let i = nums.length; i > 0; i--) {
    if (nums[i - 1] < nums[i]) {
      let nextHigherIdx = Infinity;
      for (let j = i; j < nums.length; j++) {
        if (nums[j] > nums[i - 1] && nums[j] <= (nums[nextHigherIdx] || Infinity)) {
          nextHigherIdx = j;
        }
      }
      //replacement must be in-place and use only constant extra memory
      [nums[i - 1], nums[nextHigherIdx]] = [nums[nextHigherIdx], nums[i - 1]];      
      nums.splice(i, nums.length - i, ...nums.splice(i).reverse());
      return;
    }
  }
  //sorted in ascending order as fallback
  nums.sort((a, b) => a - b);
};

//Runtime: 52 ms, faster than 99.41% of JavaScript online submissions
//Memory Usage: 35 MB, less than 33.33% of JavaScript online submissions

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more