Bigger is Greater

Bigger is Greater - A HackerRank challenge solution


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

If you liked what you saw, please support my work!

Juan Cruz Martinez - Author @ Live Code Stream

Juan Cruz Martinez

Juan has made it his mission to help aspiring developers unlock their full potential. With over two decades of hands-on programming experience, he understands the challenges and rewards of learning to code. By providing accessible and engaging educational content, Juan has cultivated a community of learners who share their passion for coding. Leveraging his expertise and empathetic teaching approach, Juan has successfully guided countless students on their journey to becoming skilled developers, transforming lives through the power of technology.