Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created September 8, 2016 10:36
Show Gist options
  • Select an option

  • Save nichtemna/d393fc7ac051ddfe96407c1e5637dcdd to your computer and use it in GitHub Desktop.

Select an option

Save nichtemna/d393fc7ac051ddfe96407c1e5637dcdd to your computer and use it in GitHub Desktop.
Hackerrank - Bigger is Greater
// https://www.hackerrank.com/challenges/bigger-is-greater
// Given a word , rearrange the letters of to construct another word in such a way that is lexicographically greater than . In case of multiple possible answers, find the lexicographically smallest one among them.
// Input Format
// The first line of input contains , the number of test cases. Each of the next lines contains .
// Constraints
// will contain only lower-case English letters and its length will not exceed .
// Output Format
// For each testcase, output a string lexicographically bigger than in a separate line. In case of multiple possible answers, print the lexicographically smallest one, and if no answer exists, print no answer.
// Sample Input
// 5
// ab
// bb
// hefg
// dhck
// dkhc
// Sample Output
// ba
// no answer
// hegf
// dhkc
// hcdk
public class GetNextWord {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
char[] array = scanner.next().toCharArray();
List list = new ArrayList();
for (char c : array) {
list.add(c);
}
System.out.println(getNext(list));
}
}
private static String getNext(List<Character> array) {
List<Character> result;
if (array.size() == 1) {
return "no answer";
} else if (array.size() == 2) {
if (getAlphPos(array.get(0)) >= getAlphPos(array.get(1))) {
return "no answer";
} else {
if (getAlphPos(array.get(0)) < getAlphPos(array.get(1))) {
swapItems(array, 0, 1);
}
result = array;
}
} else {
int pos = -1;
for (int i = array.size() - 1; i > 0; --i) {
if (getAlphPos(array.get(i)) > getAlphPos(array.get(i - 1))) {
pos = i - 1;
break;
}
}
if (pos == -1) {
return "no answer";
}
result = new ArrayList<>(array.subList(0, pos));
List<Character> sorted = new ArrayList<>(array.subList(pos, array.size()));
Collections.sort(sorted);
Character character = array.get(pos);
for (int i = 0; i < sorted.size(); i++) {
if (getAlphPos(character) < getAlphPos(sorted.get(i))) {
result.add(sorted.remove(i));
break;
}
}
result.addAll(sorted);
}
StringBuilder builder = new StringBuilder();
for (Character c : result) {
builder.append(c);
}
return builder.toString();
}
private static void swapItems(List<Character> array, int first, int second) {
char temp = array.get(second);
array.set(second, array.get(first));
array.set(first, temp);
}
private static int getAlphPos(char c) {
int temp = (int) c;
return temp - 96;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment