We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Try to solve in Java. Calculating all next lexicographical permutation using this logic. But Test#1, #2 says 4s Terminated due to time out. Any suggestion?
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));intnum=Integer.parseInt(in.readLine());Stringline="";for(inti=0;i<num;i++){line=in.readLine();// Do your stuff here}
@shraiysh Can you explain the logic here. The lexicographical permutation solution didnt work for me. It is giving me runtime error. But your code is working for me. I dont understand why.
hey i have used the same logic and implemented this problem.however my code fails for test case 1 and 2 .can u please review my code and tell where the error lies??
i posted my code in the discussions forum.please have a look at the recent comments with my username.
In my code,testcase 1 and testcase 2 are showing segmentation fault can you tell me what is the reason.I have used the same concept as described in article.
I have a confuse about this algorithm. In this tutorial, they said the suffix is 5 3 3 0 and the pivot is 2. After that, they said we can swap 2 with the smallest number, in the suffix that is greater than pivot. I misunderstood in here why 0 1 3 is the minimize prefix? In my opinion, 0 1 0 is the minimum prefix, right? Could you guys explain that point for me please. Thanks
Hi, the pivot should be smaller than the number you are swapping with, otherwise the final sequence would be lexicographically smaller than the original. So, we are finding the smallest number in the suffix, greater than the pivot, which is 3 in the tutorial.
Hope that helped.
Thanks for answering me. So, I just want to confirm that the next sequence has to be the smallest one, but it has to be bigger than the original one, right?
In your first while loop you are using condition i>=0, which results in i=-1 if its already sorted string. So your next condition becomes s[-1]<=s[0] which is resulting in segementation fault.
Hmm, I looked at your code, and incase you havent figured it out yet, you get segmentation fault beacuse you are accessing s[i-1] when i is 0; Check for this and fix it to get rid of segmentation fault
I was having the same problem....I found the error to be in the provided code (not the first time). Try adding a "free(w);" at the end of the loop in main. The sandbox was running out of memory!
Try checking is the next permutated string is actually greater than the original string or not.
Try
if(next_str.equals(str)||next_str.compareTo(str)<1)System.out.println("no answer");
permutated string=next_str
original=string
Now if the permutated string compareTo original string is smaller then print "no answer" because it is actually smaller than the original string.
It happens when pivot=swap=0 means rest of the characters are already smaller.
Would rather use more Pythonic style, for example:
def biggerIsGreater(s):
for i in range(len(s)-1)[::-1]:
if s[i] < s[i+1]:
for j in range(i+1,len(s))[::-1]:
if s[i] < s[j]:
lis = list(s)
lis[i],lis[j]=lis[j],lis[i]
return "".join(lis[:i+1]+lis[i+1:][::-1])
return 'no answer'
My Python3 code is similar to the above two code snippets. However, it doesn't use any auxiliary list lis. The purpose of my updates I,J are to find the furthest starting index of modification; for example, if w="acdb", then J=1 and I=2, to get "adbc" not "bacd".
You must have mistyped; carefully check again as an eye for detail is one of many marks of a good programmer. A fresh copy-and-paste into HackerRank, as I just did now with my own code, worked. Upvote if you like the code and ideas behind it, which I leave to users to catch up as mental exercise.
It's same with sorting. In algorith page it says :"Firstly, identify the longest suffix that is non-increasing (i.e. weakly decreasing)."
And that's the part helped me to see my algorithm's mistake. I was just finding the pair to swap, then sorting second part. It was giving correct answers for only around 96 percent of words, then looking for alternative permutations was causing timeouts.
thanks. copied this solution and refactored a little bit.
staticStringbiggerIsGreater(Stringw){char[]chars=w.toCharArray();returnnextPermutation(chars)?newString(chars):"no answer";}staticbooleannextPermutation(char[]array){inti=getLastPeakIndex(array);if(i<=0)// like "dcba", no answerreturnfalse;intj=getReplacementIndex(array,i-1);swap(array,i-1,j);// Reverse the part on the right of i - 1 to make it as small as possiblej=array.length-1;while(i<j){swap(array,i,j);i++;j--;}returntrue;}staticintgetLastPeakIndex(char[]chars){inti=chars.length-1;while(i>0&&chars[i-1]>=chars[i])i--;returni;}staticintgetReplacementIndex(char[]chars,intgivenIndex){inti=chars.length-1;while(chars[i]<=chars[givenIndex])i--;returni;}staticvoidswap(char[]chars,inta,intb){chars[a]^=chars[b];chars[b]^=chars[a];chars[a]^=chars[b];}
because it returns 0 or false if the function cannot make the bigger string in lexicographically order. for example string = "DCBA" -> this is the biggest and the function will return 0, otherwise it will returns 1 or true.
But the function always change the order to the smallest if the string was the biggest
I would suggest all to have a look at this article instead of looking for code in the disscussion. The approach in the article is readily comprehensible and decipherable.
Is there mistake in code??
We should do : arr[j] >= arr[i-1] for j>=i
but in code they did : arr[j] <= arr[j-1]?
why ? is this incorrect or am I missing something?
Bigger is Greater
You are viewing a single comment's thread. Return to all comments →
Here is a good explanation of a next lexicographical permutation algorithm:
http://www.nayuki.io/page/next-lexicographical-permutation-algorithm
This was helpful. Thanks!
Thanks. Here's the full solution in Python. Hackerrank - Bigger is Greater Solution
here is problem solution in java python c++ c and javascript programming.
HackerRank Bigger is Greater problem solution
Can u explain what have you done in java solution?? Thanks in advance.
very nice solution
good logic !!!
Try to solve in Java. Calculating all next lexicographical permutation using this logic. But Test#1, #2 says 4s Terminated due to time out. Any suggestion?
test the case when input is just one letter (e.g. p), the output should be "no answer". This solved my problem.
no it didn't solved
first of all check if same letters are repeating
int main() {
}
}
Possible implementation from cppreference.com
thanks, it solved my problem.
Thanks. It helped to pass test cases #1 and #2
such a relief!!!
Try to use
to read the input. It has 100000 test cases so Scanner won't work
can you please tell how to BufferReader to scan multiple lines of Strings with Exception Handling
here is what i did:
Thanks buddy
didn't work, i still get timeouts
I did this.. Lengthy but worked.
@shraiysh Can you explain the logic here. The lexicographical permutation solution didnt work for me. It is giving me runtime error. But your code is working for me. I dont understand why.
For me it threw a runtime error when I was not concidereing w.length = 1 cases.
It did not work. It stuck in line 20348
Scanner will work in these cases. I submitted using scanner. The problem must lie elsewhere.
thanks! that is what I needed. Don't really know why Scanner is slower than buffreader though.
Simple java solution : algorithm n wikipedia
this logic is to rev the string in O(n) time and O(1) space. can u explain, how this iis working?
its actually n/2
Use this to find no answer without solving:
https://www.hackerrank.com/challenges/bigger-is-greater/forum/comments/595411
I am having the same TLE problem in test #1 and #2. Can someone help me out?
Too helpful! Thanxx! :-)
hey i have used the same logic and implemented this problem.however my code fails for test case 1 and 2 .can u please review my code and tell where the error lies?? i posted my code in the discussions forum.please have a look at the recent comments with my username.
Helped :)
Super helpful! Learned something new today!
Nice and clear explanation!
thanks!! that was well explained
Best Explanantion! Learned something new!
very helpful, thanks
Thank you. This was so helpful and very cool.
wow! great explanation ,Thanks
Thank You! Something new everyday.
That was really helpful!! Got to learn a lot..thanks :)
great
In my code,testcase 1 and testcase 2 are showing segmentation fault can you tell me what is the reason.I have used the same concept as described in article.
Hi,
I have a confuse about this algorithm. In this tutorial, they said the suffix is 5 3 3 0 and the pivot is 2. After that, they said we can swap 2 with the smallest number, in the suffix that is greater than pivot. I misunderstood in here why 0 1 3 is the minimize prefix? In my opinion, 0 1 0 is the minimum prefix, right? Could you guys explain that point for me please. Thanks
Hi, the pivot should be smaller than the number you are swapping with, otherwise the final sequence would be lexicographically smaller than the original. So, we are finding the smallest number in the suffix, greater than the pivot, which is 3 in the tutorial. Hope that helped.
Thanks for answering me. So, I just want to confirm that the next sequence has to be the smallest one, but it has to be bigger than the original one, right?
Yes, exactly.
In your first while loop you are using condition i>=0, which results in i=-1 if its already sorted string. So your next condition becomes s[-1]<=s[0] which is resulting in segementation fault.
Hmm, I looked at your code, and incase you havent figured it out yet, you get segmentation fault beacuse you are accessing s[i-1] when i is 0; Check for this and fix it to get rid of segmentation fault
I was having the same problem....I found the error to be in the provided code (not the first time). Try adding a "free(w);" at the end of the loop in main. The sandbox was running out of memory!
Guys think about the logic for a few minutes before looking at this!
Great Tutorial
extremely helpful! thanks a lot!
thank you very much
I tried to implement same algorithm. But only got test0 and test3 successful. I have written following code. Where might I be wrong?
Try checking is the next permutated string is actually greater than the original string or not. Try if(next_str.equals(str)||next_str.compareTo(str)<1)System.out.println("no answer"); permutated string=next_str original=string Now if the permutated string compareTo original string is smaller then print "no answer" because it is actually smaller than the original string. It happens when pivot=swap=0 means rest of the characters are already smaller.
Thanks @devstarj this http://www.nayuki.io/page/next-lexicographical-permutation-algorithm could be posted in the topics for Java solution
Awesome! Love the hackerrank community.
very nice
Thanks it was very helpful
I love you
Thank you ...
Thanks for the logic! Great help.
thanks for posting this algorithm. here's a python 3 solution based on this algorithm
no need check ord(s[i]) < ord(s[j]), just s[i] < s[j] is enough.
this code like in C
Would rather use more Pythonic style, for example:
def biggerIsGreater(s):
what [ : : -1] it does after range() ??
it reverse the range.
Got it, thanks.
how u develop that level of thinking
My Python3 code is similar to the above two code snippets. However, it doesn't use any auxiliary list
lis
. The purpose of my updatesI,J
are to find the furthest starting index of modification; for example, ifw="acdb"
, thenJ=1
andI=2
, to get"adbc"
not"bacd"
.i tried same solution, test cases are failng
You must have mistyped; carefully check again as an eye for detail is one of many marks of a good programmer. A fresh copy-and-paste into HackerRank, as I just did now with my own code, worked. Upvote if you like the code and ideas behind it, which I leave to users to catch up as mental exercise.
this is a hell of a lot simpler then the nayuki page
http://stackoverflow.com/questions/1622532/algorithm-to-find-next-greater-permutation-of-a-given-string
Thanks a Lot.I didnt think that it is this much simple
Learnt new logic. Very helpful. Thanks!
That moment when your inital algorithm was exactly the same
Thank you so much.It really helped a lot.
Thank you so much!
Also remember to include the edge case where the length of the word is 1.
yeah !!! that taught me the algo!! thanks!1
Thank you so much!
I think there is problem in the algorithm, instead of reversing the subarray , it should be sorted.
It's same with sorting. In algorith page it says :"Firstly, identify the longest suffix that is non-increasing (i.e. weakly decreasing)." And that's the part helped me to see my algorithm's mistake. I was just finding the pair to swap, then sorting second part. It was giving correct answers for only around 96 percent of words, then looking for alternative permutations was causing timeouts.
good job,better than editorial!
nice one
Thanks for the blog
thanks. copied this solution and refactored a little bit.
thanks bro!! helpful..
thank so much :))
Hi,
I have created a tutorial for you all. have a look, i hope it will help you to solve the problem.
Here is the video explanation of my solution in O(n) time -
https://youtu.be/BMbeeB_57Pk
Here's my JS solution. I started from the end of the string and worked backwords until I found a character that is less than something previous:
Please can you explain the solution?
Thanks great explanation
Very helpful article. Thanks!
very helpful.thanks!
Great solution!!!! I was trying from last two days and finally found this ..thanks!
nice one!
int main() { int t; cin >> t; while(t--) { string w; cin >> w;
}
can you explain why you took (next_permutation ==0) and what will happen with that condition
because it returns 0 or false if the function cannot make the bigger string in lexicographically order. for example string = "DCBA" -> this is the biggest and the function will return 0, otherwise it will returns 1 or true. But the function always change the order to the smallest if the string was the biggest
I would suggest all to have a look at this article instead of looking for code in the disscussion. The approach in the article is readily comprehensible and decipherable.
This one is great.
really thanks for this man ... I really needed this next_permutation raw logic..
Very well explained by the person in the link above.
Thanks for sharing!!
cool. thanks man. I've been doing this exercise for two days..
this is a very good explanation!
here is my solution in JAVASCRIPT :
HackerRank Bigger is Greater problem solution
*Hi , I have done the problem through the following code. Can anyone explain me where I commited the mistake *
I appreciate your help
thanks in advance
Thanks a lot!
Is there mistake in code?? We should do : arr[j] >= arr[i-1] for j>=i but in code they did : arr[j] <= arr[j-1]? why ? is this incorrect or am I missing something?
thank you so much i was missing the last sorted suffix part
Brilliant. Thanks!