Bigger is Greater

Difficulty: Medium Source: Hacker Rank
Feature image

Problem

Lexicographical order is often known as alphabetical order when dealing with strings. A string is greater than another string if it comes later in a lexicographically sorted list.

Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria:

  • It must be greater than the original word
  • It must be the smallest word that meets the first condition

For example, given the word w = abcd, the next largest word is abdc.

Complete the function biggerIsGreater below to create and return the new string meeting the criteria. If it is not possible, return no answer.

Function Description

Complete the biggerIsGreater function in the editor below. It should return the smallest lexicographically higher string possible from the given string or no answer.

biggerIsGreater has the following parameter(s):

  • w: a string

Read more on the challenge page…

My Solution

I’m providing the solution for Python and JS, please leave on the comments if you found a better way.

The idea of the algorithm is quite simple, we need to modify the values of the array as far as possible to the right, that way we can guarantee the minimum increment.

The idea of the solution is a well-known algorithm which is already well explained in Wikipedia . Read the article if you want to know all the details.

I created however a chart that summarizes the procedure in a few steps and with an example:

Next Permutation Algorithm Example

Next Permutation Algorithm Example