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.

HackerRank Bigger is Greater Solution
HackerRank Bigger is Greater Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Bigger is Greater Solution

Task

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
no answer
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
no answer
no answer
acbd
abdc
fedcbabdc

HackerRank Bigger is Greater Solution

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
            printf("no answer\n");
    }
    return 0;
}

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());
        else printf("no answer\n");
    }
    return 0;
}

Bigger is Greater Solution in Java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Solution {
	private static final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
	private static final PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
	public static void main(String[] args) throws NumberFormatException, IOException {
		int testCount = Integer.parseInt(bufferedReader.readLine());
		while (testCount-- > 0) {
			String w = bufferedReader.readLine();
			String nextWord = getNextPermutation(w);
			if (nextWord != null) {
				printWriter.println(nextWord);
			} else {
				printWriter.println("no answer");
			}
		}
		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();
	}
}
Ezoicreport this ad

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)
    else:print 'no answer'

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)
        return "no answer";
    
    // 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('');
}

Bigger is Greater Solution in Scala

object Solution {
  import scala.util.Sorting._
    
  def getData(): List[Array[Char]] = {
    (for (i <- 1 to readInt) yield
      readLine.toArray).toList
  }
  
  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)
        case None => println("no answer")
    }
  }
}

Ezoicreport this adBigger 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
  readln(t);
  while t>0 do begin
    readln(s);
    if last(s) then writeln('no answer')
               else writeln( next(s));
    dec(t);           
  end;
end.

Disclaimer: This problem (Bigger is Greater) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank ACM ICPC Team Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad