# HackerRank Bigger is Greater Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Bigger is Greater Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

## HackerRank Bigger is Greater

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

Example

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.

biggerIsGreater has the following parameter(s):

• string w: a word

Returns
– string: the smallest lexicographically higher string possible or `no answer`

Input Format

The first line of input contains T, the number of test cases.
Each of the next T lines contains w.

Constraints

• 1 <= T <= 105
• 1 <= lengthofw <= 100
• w will contain only letters in the range ascii[a..z].

Sample Input 0

```5
ab
bb
hefg
dhck
dkhc
```

Sample Output 0

```ba
hegf
dhkc
hcdk
```

Explanation 0

• Test case 1:
`ba` is the only string which can be made by rearranging `ab`. It is greater.
• Test case 2:
It is not possible to rearrange `bb` and get a greater string.
• Test case 3:
`hegf` is the next string greater than `hefg`.
• Test case 4:
`dhkc` is the next string greater than `dhck`.
• Test case 5:
`hcdk` is the next string greater than `dkhc`.

Sample Input 1

```6
lmno
dcba
dcbb
abdc
abcd
fedcbabcd
```

Sample Output 1

```lmon
acbd
abdc
fedcbabdc```

## HackerRank Bigger is Greater Solution

### HackerRank Bigger is Greater Solution in C

```#include <stdio.h>
char s[500];
int main()
{
int t,j;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
int l=strlen(s);
int i=l-1;
int f[300]={0};
while(i>0&&s[i]<=s[i-1])
{
f[s[i]]++;
i--;
}
if(i)
{
f[s[i]]++;
f[s[i-1]]++;
for(j=0;j<i-1;j++)
printf("%c",s[j]);
for(j=s[i-1]+1;j<='z';j++)
if(f[j])
break;
f[j]--;
printf("%c",j);
for(i='a';i<='z';i++)
for(j=0;j<f[i];j++)
printf("%c",i);
printf("\n");

}
else
}
return 0;
}```

### HackerRank Bigger is Greater Solution in Cpp

```#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

string s;

int main() {
int tc;
scanf("%d", &tc);
while (tc--) {
cin >> s;
if (next_permutation(s.begin(), s.end())) printf("%s\n", s.c_str());
}
return 0;
}
```

### HackerRank Bigger is Greater Solution in Java

```import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class Solution {

private static final PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

public static void main(String[] args) throws NumberFormatException, IOException {
while (testCount-- > 0) {
String nextWord = getNextPermutation(w);
if (nextWord != null) {
printWriter.println(nextWord);
} else {
}
}
printWriter.flush();
}

private static String getNextPermutation(String w) {
int length = w.length();
StringBuffer word = new StringBuffer(w);
int i = length - 2, j = length - 1;

while (i >= 0) {
if (word.charAt(i) < word.charAt(i + 1)) {
break;
}
i--;
}

if (i < 0) {
return null;
}

while (j > i) {
if (word.charAt(j) > word.charAt(i)) {
break;
}
j--;
}

char swapSpace = word.charAt(i);
word.setCharAt(i, word.charAt(j));
word.setCharAt(j, swapSpace);

StringBuffer biggerWord = new StringBuffer();
for (int k = 0; k <= i; k++) {
biggerWord.append(word.charAt(k));
}

for (int k = length - 1; k > i; k--) {
biggerWord.append(word.charAt(k));
}

return biggerWord.toString();
}
}```

### HackerRank Bigger is Greater Solution in Python

```def next(a):
i = len(a) - 2
while not (i < 0 or a[i] < a[i+1]):
i -= 1
if i < 0:
return False
j = len(a) - 1
while not (a[j] > a[i]):
j -= 1
a[i], a[j] = a[j], a[i]
a[i+1:] = reversed(a[i+1:])
return True
for i in xrange(input()):
w = list(raw_input().strip())
if next(w):
print ''.join(w)

### HackerRank Bigger is Greater Solution using JavaScript

```function processData(input) {
var input = input.split('\n').slice(1);
var i=0;
for(i=0; i<input.length; i++) {
console.log(nextPermutation(input[i].split('')));
}
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});

process.stdin.on("end", function () {
processData(_input);
});

function nextPermutation(array) {
// Find non-increasing suffix
var i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i])
i--;
if (i <= 0)

// Find successor to pivot
var j = array.length - 1;
while (array[j] <= array[i - 1])
j--;
var temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;

// Reverse suffix
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
return array.join('');
}```

### HackerRank Bigger is Greater Solution in Scala

```object Solution {

import scala.util.Sorting._

def getData(): List[Array[Char]] = {
(for (i <- 1 to readInt) yield
}

def checkWord(wrd: Array[Char]): Option[String] = {
for{ i <- wrd.length - 1 to 0 by -1
j <- wrd.length - 1 until i by -1 } {
if (wrd(i) < wrd(j)) {
val tmp = wrd(j)
wrd(j) = wrd(i)
wrd(i) = tmp

val (fst, lst) = wrd.splitAt(i + 1)
quickSort(lst)
return Some(fst.mkString + lst.mkString)
}
}
return None
}
def main(args: Array[String]) {
for (wrd <- getData())
checkWord(wrd) match {
case Some(w) => println(w)
}
}
}```

### HackerRank Bigger is Greater Solution in Pascal

```function last(s: string): boolean;
var c, c1: char;
begin
c:= 'z';
for c1 in s do begin
if c<c1 then Exit(false);
c:= c1;
end;
last:= true;
end;

function next(s:string): string;
var r, k: byte;
c: char;
begin
r:= length(s)-1;
while s[r]>=s[r+1] do dec(r);
k:= r+1;
while (k<=length(s)) and(s[r]<s[k]) do inc(k);
dec(k);
c:= s[r]; s[r]:= s[k]; s[k]:= c;
inc(r);
k:= length(s);
while r<k do begin
c:= s[r]; s[r]:= s[k]; s[k]:= c;
inc(r);
dec(k);
end;
next:= s;
end;

var t: longint;
s: string;
begin
while t>0 do begin
else writeln( next(s));
dec(t);
end;
end.```

Disclaimer: This problem (Bigger is Greater) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

Sharing Is Caring