6 kyu
longest_palindrome
4,283 of 11,088kgashok
Loading description...
Fundamentals
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
Nice Kata!
With s = "lpllmdokuhqokgkmwyrfuzzcjgozlkqiqmhgdmvopiqkdlppqxjwyiyvhbchfvvsr": 3 should equal 5
Can anyone help me to find 5?
Python
There is indeed an issue in the reference solution
Not possible to create these palindrome length since they are longer than the original string.
Updated JavaScript
This comment has been hidden.
Approved by someone.
Nice one
( JS )
Tests do not allow updating to
Node 14.x
; they time out. It appears the kata requires micro-optimisation. ( It's also lacking random tests. )It would be very good to have this kata updated to
Node 14.x
, soNode 10.x
can be removed from Codewars. This is one of no more than twenty-odd kata stuck inNode 10.x
( see https://github.com/codewars/content-issues/wiki/List-of-JavaScript-Kata-to-Update#list-of-node-10x-kata ).I would love to fix this. But the scars of some very rude snobs here on CodeWars discourage me from trying anything new.
Less than twenty stuck in
Node 10.x
now. And now withNode 18.x
,Node 10.x
,12.x
and14.x
will be able to be removed. Please?Everybody is doing two nested loops ( apart from some hardcoding ); it's a matter of sizing the Gettysburg test, random tests aren't necessary to get out of
10.x
.Updated
The "attempt" tests are on the edge of timing out in javascript... It may be worth reducing their required time a little (e. g. reduce the number of tests...) It makes you think really hard about optimization, that's good. But even with optimization it does pass only sometimes (i.e. not timing out)...
The Kata was updated to allow for non-optimized solutions.
WHat is the input format ? Consists of only lowercase letters or any kind of characters? Do space separated palindromes or palindromes formed using mixed case letters count ? for ex : In string "I coulD am madl bb" , which is largest palindrome substring "lD am madl", "am ma" or "bb"
Python fork updated to new framework + added random tests (
O(n^2)
solutions should still pass).approved
Rust translation
For string "abcdefghba" the result should be 2 in my opinion:
"ab" -> "ba"
So why tests show me that expected value is 1?
Java
Probably because 'ab' is not a palindrome?
I believe this is a little bit hard for 6kyu; nevertheless, it was a great practice.
This comment has been hidden.
'123454321'
is the longest palindrome, hence returning 9My bad! Thank you.
STDERR Unhandled rejection TestError: Expected: 1, instead got: 2
Why??
Language?
js
Using nested loops my code works fine in tests but when I try to attempt it returns Out of Time Execution :( , any hint? :p
Don't use nested loops.
Thank you, very useful your comment, you're a genius
I was joking, you probably should use nested loops, just don't use more than 2. Note some methods are loop-alike, so be aware of that.
Thanks bro! jaja love u! :o
what an amazing kata this was.. thank you!
Glad you liked it! Cheers,
No random tests in JS
Added random tests
I recommend adding a tests for repeating characters in a string of more than 20 characters.
eg. doTest("lolollolollolollolol", 20); doTest("abcdefghijklmnopqrstuvwxyz lolollolollolollolol", 20);
Reason being my solution was very different from most others and I could have submitted without fixing these failing cases.
Added to Example Test cases. Thanks,
UndefinedBehaviorSanitizer:DEADLYSIGNAL ==1==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x000000000000 (pc 0x000000425a43 bp 0x7ffca798fd30 sp 0x7ffca798f7b0 T1) ==1==The signal is caused by a READ memory access. ==1==Hint: address points to the zero page. ==1==WARNING: invalid path to external symbolizer! ==1==WARNING: Failed to use and restart external symbolizer! #0 0x425a42 (/workspace/test+0x425a42) #1 0x428802 (/workspace/test+0x428802) #2 0x426d2e (/workspace/test+0x426d2e) #3 0x42675d (/workspace/test+0x42675d) #4 0x42644b (/workspace/test+0x42644b) #5 0x42d5f5 (/workspace/test+0x42d5f5) #6 0x425c3d (/workspace/test+0x425c3d) #7 0x7fdf3a378bf6 (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6) #8 0x404909 (/workspace/test+0x404909)
UndefinedBehaviorSanitizer can not provide additional info. ==1==ABORTING
i get this error and am not understanding why this happens. The code runs normally on Sublime.
https://docs.codewars.com/training/troubleshooting#c-error-undefinedbehaviorsanitizer-segv-on-unknown-address-0x000000000000
Thanks.
This comment has been hidden.
Please read this paragraph: https://docs.codewars.com/training/troubleshooting#print-input
I'd like to know what the optimal time complexity for this would be
Question about spaces: In example "I like racecars..." would "I li" count as a palindrome or not? Without space: "ili". Suggests making this clear by test or in description.
This comment has been hidden.
Since I posted the issue, I already have a working code in my local. Too eager to submit, looking forward for kgashok's response.
@Lrac, not an expert in Ruby. Sorry!
This comment has been hidden.
Hi. Enjoying the problem, but not sure how this works, based on the following:
Shoud this be 1?
Test.assertNotEquals(longestPalindrome("zyabyz"), 6...
And think this might be 5 - the "zzbaa" combination(?) From the examples: "zzbaabcd" -> 4
Thought I understood the problem, but having seen these, I'm not sure of the rules. Thanks!
u need 'baab' from the example "zzbaabcd", then it's 4
Ruby 3.0 should be enabled, see this to learn how to do it
Enabled in this fork
The return value of the parameter abcdefghba should be 2.
.
@cubking, as to
abcdefghba
, the longest palindrome is only one character long. If it wereabba
, then the longest palindrome would be of length 4. If it wereaa
orbb
, then the longest palindrome would be of length 2. I hope this helps.I think it would be nice to state that white spaces are included for the palindrome count in the kata description.
Find the length of the longest substring in the given string s that is the same in reverse.
As an example, if the input was “I like racecars that go fast”, the substring (racecar) length would be 7
somebody please explain what he wants ME to do here?? like whats the goal what should i do am so confused
every 6kyu question is like that,its just so hard to understand
the question ask you to write a method to find the linges palindrome form the given string palindrome is if a word is read in reverse string it spells the same example abba - is same if read in reverse
so if a string is given as "hello world abba, that is kayak" in here there are 2 palindrome (substring) abba and kayak but the longest one is kayak (length of 5)
so writing a function to find the longest palindrome and return it
hmm,okay! i hope i got the idea right, thanks alot
There is an UB in C++ tests.
That's in your code not in tests, as I've just completed the C++ version and there were only few warning of comparision between unsigned long and int.
I'm getting this strange error in Python when I try to retreive the first item in the list. It says that list index 0 is out of range, meanwhile when I run my code through other python compilers like Python Tutor I am not receiving that error.
Traceback (most recent call last): File "main.py", line 3, in test.assert_equals(longest_palindrome("a"), 1) File "/home/codewarrior/solution.py", line 23, in longest_palindrome longest = palinCounts[0] IndexError: list index out of range
What time should be a optimal for the last test (the long one)?
shouldn't test case "aab" -> 3 ? It says it returns two, but "aba" is 3 chars long
Who said you can re-arrange the letters? You can only use exactly what's given, hence 'aa' is longest palindrome here.
"aab" return 2
In the Gettysburg address test case, I found 'ranynar', which is a palindrome of length 7. But it returns saying it should be zero. Is this an error, or am I making a mistake?
Yes, 7 is the expected answer. Your solution returns
0
. Is that what you are wondering?My solution returns the correct answer (the length is correct when I print it out), but the error says it should be returning 0 instead of 1.
Your code is failing the test case previous to the Gettysberg address test case. The input string for that test case is an empty string.
slaps forehead always the easiest solution! Something I need to work on. Thank you!
You are welcome.
This comment has been hidden.
is can "(nothing)" be palindrom? size of "(nothing)" == 0 or "(nothing)" == 1? nothing = "space"
This comment has been hidden.
No need for further replies, i figured it out. Thanks
This comment has been hidden.
What is the Big-O notation of your solution? As long as you do it in
O(n)
orO(n**2)
, it should pass the tests.thanks for the reply but I'm not sure if i understand what you're saying...
If you have more than two nested
for
loops, Big-O is very likely to be greater thanO(n**2)
. Read this.However, there are two basic approaches to solving this kata:
Approach_2 will help eliminate timeouts, especially for input strings that are really long.
More importantly, avoid using the chained calls
.split().reverse().join()
approach to check for palindrome. Instead use the iterative method and two indexes to check whether the string is a palindrome.This comment has been hidden.
I have to assume (even at the risk of being wrong) that @ylksCoding is not aware of
Dynamic Programming
orManacher's
algorithm. So, I simplified my response to himso that he continues his struggle from where he left off. Of course, after solving
the problem, I would strongly recommend him to investigate the dynamic programming approach
as well as Manacher's algorithm.
Only reverse one time, otherwise you will time out on large strings.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
You might want to add
Test.assertEquals(longestPalindrome("abcacba"), 7)
as a test case. I've seen a solution which effectively iterates the array, for each character looks up the next index of of that character and decides if it's a palindrome -- this case will fail that method because it will only considerbcacb
as a palindrome, since a -> a would only get the first half of the palindrome in the string.can you please tell me how it will take only bcacb.as according to my code it will take character from end so "abcacba" it will take "a" from end and index wil be start from 0 and it is found at ""0"" index because index is search from 0th index. therefore substring will become "abcacba"....
This comment has been hidden.
These are not palindromes! Palindromes are the same forward and backward. Racecar is a palindrome. Racecars is not a palindrome because it would be sracecar when spelled backward. No one refers to a palindrome within a word or string of characters. If you need help on what a palindrome is, reference the link.
https://examples.yourdictionary.com/palindrome-examples.html
gmanley, read the kata description again:
And in the example, racecar is a palindrome. You're working with substrings here.
Chrono79. Look at the examples. Palindromes are not substrings within a word. They are words or lines when written backward, spell the same thing. This kata is a non-sensical task. Your instructions do not make sense when you call any substring that can be written in reverse a palindrome. Words have meaning. A problem to find actual palindromes would be solved differently. You could improve the kata by determinig if a word or phrase is a real palindrome. Below is another link if you need more reference on what a palindrome is.
https://en.wikipedia.org/wiki/Palindrome
Thanks, but they're not my instructions.
From your links:
A string (or substring) is a sequence of chars.
That is not the correct interpretation. But, I'm not going to argue anymore. Good luck!
strings can be palindromes. strings can also be substrings. therefore palindromes can be substrings. your argument is nonsensical.
This comment has been hidden.
If you splitted the words in the string, it could be why it fails the random test. I found out that probably it generates spaces and consider it all as a word. The test is wrong, not your solution.
This comment has been hidden.
Keeps on timing out - not sure if the server or me, but solution works.
If you modify your
isPalindrome
function not to use chained calls (.split().reverse().join()), it might not timeout.yeah, i think that's the problem but also tried that and it keeps timing out
I like it, it's easy to understand but a bit challenging. Brute force is possible, making this kata solvable for many at this level.
After dozens of timed out errors I gave up, tried an accepted solution from the Solutions section and it also timed out. More specifically sometimes it times out, sometimes it doesn't. This Kata is bad because it times out on an accepted solution 50% of the time. It should be removed.
Sorry that you feel frustrated about this kata.
The timeout happens because your algorithm might be of complexity
O(n^3)
or above.If you can reduce the complexity, the timeouts should go away.
You reduce the complexity, by eliminating/refactoring the number of
nested for-loops that might be in your code.
Tweak your logic that already works in the following manner to gain performance: Instead of initiating the search for a substring with minimum size, start with a substring of maximum size and work your way down.
Almost 2000+ (out of5000) have solved it, so can you. Go for it!
This comment has been hidden.
This comment has been hidden.
why (longest_palindrome("abcdefghba"), 1) should equal 1 ? the result should equal 2 because substring "ab" it is right !
This comment has been hidden.
I got 2
I don't see why "ab" should be a palindrome
I am at my third working solution which make time out on the attemps solution. I'm a bit tired.
This comment has been hidden.
Tweak your logic that already works in the following manner to gain performance: Instead of initiating the search for a substring with minimum size, start with a substring of maximum size and work your way down.
Does anybody know why the Java test expects 1 instead of 2 for the string "zyabyz"?
Why would the answer be 2 for that? There's no substring with a length of 2 that is a palindrome.
Thanks, thats correct of course. I searched for something wrong in my solution. Now it's working... but it times out. :)
Can't deal with 1169 length. Time out old friend
Python: No randomized testing
Python has random tests, resolving this
Missing language. Nice.
Please clarify.
When I try to submit a result or run sample tests, this Kata gives me the "Missing language" error. I'm using C.
It works for me in C (and there are 69 completions in C), so it doesn't seem a kata issue. Check if it is related to this CW issue or raise one issue there.
It works for me too, now. I guess it was just a random bug. It was using the
foo()
function when the bug occured. It also seemed to be testing for multiplication.This comment has been hidden.
This comment has been hidden.
same
Timing out problem may be due to calling reverse multiple times, do that only once.
6 kyu? This kata is so difficult
not really. think through it logically and come up with a brute Force approach initially and then try optimizing it.
I agree with zttr. It's actually pretty challenging for a 6kyu. For instance I have a working "brute force" approach which works in my test cases on my IDE but when I try to use it through the kata portal it times out. Not really sure how to optimise it any further :(.
This comment has been hidden.
ISSUE: my code is failing because "Expected: equal to 0, Actual: 1"
That's the test's fault though right? you cant have a string and not have a letter and a letter is a palindrome of length 1.
Empty strings have 0 letters.
doTest("zyabyz", 1); z to z is 6. why 1? can who explain, please
zyayz
,zyabayz
orzybabyz
would have been valid palindromes of size 5, 6 and 6 respectively.Although
zyabyz
is not a valid palindrome, every letter by itself is a palindrome of size1
.And so the correct return value is 1.
Thank you, I understood the situation
Ruby
So my code works for the sample tests but not for the test cases. Here's what I get: " Time: 1801ms Passed: 6 Failed: 1 Exit Code: 1 Test Results: Test Passed: Value == 1 Test Passed: Value == 2 Test Passed: Value == 2 Test Passed: Value == 2 Test Passed: Value == 4 Test Passed: Value == 9 Expected: 1, instead got: 5 " Is anyone facing the same issue?
Also, how can I print the all tests (or the failed tests) in the output? I read a couple responses saying that I should do that, but I don't know how to. Plz reply if you know how (for Ruby).
Thanks
I don't understand this question.
See responses to teddy shell's query below.
I did not receive any out of bounds exception (I did my solution in C), instead the system compared the characters to something out of bounds which made me fail some tests. When I fetched out of bounds before they could happen, everything was fine. Dunno if that's the right place to put in this feedback, I'm relatively new here :-). Cheers!
This comment has been hidden.
"yz" is not a palindrome. The string contains both "yz" and "zy", but they are not palindromes. "yzy" and "zyz" would be palindromes. (https://en.wikipedia.org/wiki/Palindrome)
This comment has been hidden.
A palindrome is a sequence of letters which reads the same backward as forward, e.g.
"rotator"
(see Wikipedia). There aren * (n + 1) / 2
substrings in every string, e.g."palindrome"
has substrings"palindrome"
,"palindrom"
,"alindrome"
,"palindro"
,"alindrom"
,"lindrome"
, ... Find the length of the longest substring that is a palindrome.E.g.
"asequenceofletters"
contains the substring"ette"
which is a palindrom. Result: 4.in 'palindrome' are 55 substrings? it's correct ??
return the longest substring(which is palindrome)'s length... It's really confuse
New translations available: C, C++, and Java
approved some time ago
This comment has been hidden.
Check your outer for loop -
range(len(s))
? Ifs
is of length 1, thefor
loop does not execute. You probably needrange(len(s)+1)
?I don't understand why "abcdefghba" is a palindrome at all, and with "length 1" ?
https://en.wikipedia.org/wiki/Palindrome
A palidrome is a sequence of letter, numbers, etc that reads the same forwards as it does backwards. Therefore a 1 letter string can be said to be a "palindrome" because it reads the same if all the letters are reversed (in this case just one letter). From this we can deduct that any string will contain, at a minimum, a palindrome with a length of 1.
Technically, it is not, but the longest palindrome substring within that string is a string of length 1. In that case, any random letter in the original string is considered a palindrome on it's own.
This comment has been hidden.
Since the goal is to find the longest palindrome, you could start with the longest string and start pruning downwards. You could research and adapt efficient string algorithms that already exist - https://en.wikipedia.org/wiki/String_searching_algorithm. Happy coding!
This comment has been hidden.
"ba" is not a palindrome. "aba" is a palindrome, because if you reverse it, it will stay the same.
Oh I see thanks! I think I'm approaching the problem in a different way that is why I'm having a different answer.
Perhaps some more tests are needed to cover more complicated strings: http://stackoverflow.com/a/16776621/16777
Very good suggestion.
My solutions takes about ~450ms for all cases, but other users think that solution that takes ~2.5 seconds is the cleverest and that is the best practices. I think that is is wrong. Probably solutions should have some additional indicators ?
Yours seems to take just as long as the others. Varies from 2.5 seconds up to 7 seconds randomly.
Codewars feature request is not a kata suggestion, resolving this
I see many implemetation with O(n*n) complexity. It would be great to add a huge test case (like 10.000 characters) so solutions which are too slow are excluded
There're already 4700+ solutions. Nobody's going to add performance tests now.
This comment has been hidden.
aba
is a palindrome of length 3. So result expected is 3.abba
is a palindrome of length 4. So result expected is 4.abcba
is a palindrome of length 5. So result expected is 5.abcdba
is not a palindrome.Thank you for the response. I still don't understand. If "abcdba"'s result is 1. Why is the result of "aab" is 2? My thinking is that the answer is 2, because the reversed string of "aab" is "baa" and the longest palindrome that repeats itself in both "aab" and "baa" is "aa". Could you please explain how "baablkj12345432133d" results in 9?
Now I get it. "ba" is not a palindrome. "aba" is a palindrome, because if you reverse it, it will stay the same. Thank you for helping me.
Getting an error on tests and submit that doesn't seem to have anything to do with my code.
STDERR: Error: unrecognized flag --no-warnings Try --help for options
I'm passing all 10 tests on submit, but it fails because of this error.
I have the same issue. I'm doing the kata in js, if that helps with the debugging.
Same Issue, again in js.
Same issue, also js.
Same issue, using Javascript.
Best Regards,
Same for me.
Why we jsER got the same STDERR info? Really confusing.
Also having the same error. I tried removing all ES2015 and ES6 features and still won't run.
the --trace-warnings flag that can not be found got introduced in node v6.0.0 The version used to run the solutions provided is v0.10.33, and the option to change it to v6 is disabled. I believe this is the problem. My solution passes all unit tests. This issue has been around and unadressed for 3 weeks. Pretty crappy support.
I would suggest you save your solution in https://repl.it and move on to the next kata which i hope is not as shoddy.
You are right. And there is no way to switch back to v6. I have no clue of how to fix this.
This is now resolved, almost magically. Thanks,
This comment has been hidden.
nodejs v6.0 support please~
This comment has been hidden.
Hello,
I have a problem. All my tests are passing, keep failing on submit. ✘ Expected: 1, instead got: 2 without any explanation what is the failing test about. Please advise.
Below is a dump from the console:
Object {type: "execution success", stdout: "PASSED::Test Passed: Value == 1↵PASSED::Test P…Value == 9↵FAILED::Expected: 1, instead got: 2↵", stderr: "
expect': Expected: 1, instead got: 2 (Test::…rom
assert_equals'↵ from<main>'↵", exitCode: 1, wallTime: 345…} exitCode : 1 languageVersion : "2.3.x" messageTime : 5 queueTime : 3 receivedAt : 1470168743719 responseAt : 1470168744253 result : Object setupTime : 181 stderr : "
expect': Expected: 1, instead got: 2 (Test::Error)↵ fromassert_equals'↵ from
<main>'↵" stdout : "PASSED::Test Passed: Value == 1↵PASSED::Test Passed: Value == 2↵PASSED::Test Passed: Value == 2↵PASSED::Test Passed: Value == 2↵PASSED::Test Passed: Value == 4↵PASSED::Test Passed: Value == 9↵FAILED::Expected: 1, instead got: 2↵" token : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjaXBoZXJlZCI6WyJzZXR1cCIsImZpeHR1cmUiXSwiaWQiOiI1N2EwNjYyNzUzYmEzMzc1OWEwMDAwOGYiLCJjb21wbGV0ZWQiOmZhbHNlLCJ3YWxsVGltZSI6MzQ1LCJpc3MiOiJjb2RlcnVubmVyIiwiZXhwIjoxNDcwMTY4ODY0MjUzfQ.q4v2BKYzYlvOguBRZAem6l-qrIvou6Y5OYG0UpqyCFk" totalTime : 534 type : "execution success" wallTime : 345When I 'Run Tests', they all pass and when I Submit, I receive 1 failure. Problem is, the test is not shown so I don't know why it's failing.
This is all I see: ✔ Test Passed: Value == 1
✔ Test Passed: Value == 2
✔ Test Passed: Value == 2
✔ Test Passed: Value == 2
✔ Test Passed: Value == 4
✔ Test Passed: Value == 9
✘ Expected: 1, instead got: 2
print information to the console
all my tests are passing. keep failing on submit. getting expected 1 got 0. i covered '' and 'a' - what else?
Tip: as long as the string length > 0 then you will have at least one palindrome substring
Best Regards,
can't submit final solution. receive server time outs. don't know is it a server faoult or my code. does anyone have final tests?
I'm having a similar issue. All tests pass, but final submission fails with time out error.
"FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"
is one the test cases. I suggest you adopt a different logic so your solution does not time out?
This comment has been hidden.
The "hidden" test cases (which are not exposed) may be causing the
IndexError
here on codewars.HINT: The maximum valid index into a string of text is len(text)-1. For e.g., if the text is "abcde" then len(text)-1 = 4. IndexError is probably occurring because you are accessing a character at a position (index) beyond the valid maximum value.
I tried addressing it using the hint you provided and do not go out of bounds on the valid index references, but it's still not working. It works fine for me in IDLE.
Some of the hidden test cases:
"I like racecars that go fast"
->7
"abcdefghba"
->1
""
->0
you mark your comment as having spoiler content, but people who didn't solved this kata will not see it ;-)
Yeah I cannot see kgashok's response.
I've removed the spoiler flag.
@kgashok, can you please explain the 2nd hidden test case? I don't see a palindrome :(
The 2nd hidden test case is
"abcdefghba"
. There exists no substring within the string that is a palindrome. Therefore the length of the longest substring is any of the letters. So the answer is1
. I hope this helps.When I click "run tests" I get 7 of 7 passed. When I try to "submit", I get 7 pass and 1 fail. But there's no way to see this 8th test or find out why my code failed. Am I missing something?
OK, I figured it out. I really don't like the "secret test" angle. Why not put this test in the initial "run tests" round? Or at least let coders see the failed test so they can puzzle out why it fails?
For the record, I too dislike secret test cases. However, there is this possibility of writing code just to pass the test cases. Also, the secret tests inevitably requires a higher order of thinking to pass. For e.g. handling edges cases, etc.
I am struggling with submitting the solution. When i run test i get 7 of 7 passed but when i try to submit it, i see 7 pass and 1 fail. What do i do here now so that i can submit the solution?
I had the same problem. The test I failed initially was
"abcdefghba"
. It should return1
. If your code does not return1
for this case, try to figure out why. It's a clever puzzle. I still think this test (or some variation) should be in the description or test cases.I second that, now it is clear what he's looking for. I thought palindrome are words that read from left to right and right to left AND they are in a contiguous order, one charchter after the other.
This comment has been hidden.
The maximum valid index into a string of
text
islen(text)-1
. For e.g., if thetext
is "abcde" thenlen(text)-1
= 4.IndexError
is probably occurring because you are accessing a character at a position (index) beyond the valid maximum value.Test cases need to include titleized words as well. Or the description should be updated to indicate the exclusion of mismatching case palindromes (Racecar != racecaR).
Some solutions will return 5 for "Racecar" rather than 7 but still pass.
Unless my understanding of a palindrome is incorrect, racecar is still a palindrome even when it's titleized (Racecar).
Your understanding is correct. All the test cases don't necessarily deal with legal English words/sentences. And therefore, I more inclined to update the description as suggested by you.
In the example:
Shouldn't "zzbaabcd" return 5?
Length of
baab
is 4. How do you figure?Whoops, I mistook 'aabzz' as a palindrome. That's embarassing.
Cheers,
This comment has been hidden.
This comment has been hidden.
In fairness to myself though, I just completed a course in which EVERYTHING (right down to picking my nose) is written as a separate function, and I think my code reflects that :)
This comment has been hidden.
I've noticed a trend in the popular kata answers to try and be as concise as possible. But sometimes I like to break everything out into a separate function, since it can help to document what is going on.
On the other hand, the longer and the more functions the code gets, the more inertia there is against trying to read it. It's the classic too long--didn't read dilemma.
Lately I seem to be editing my code to as few lines as possible, unless expanding things makes it more obvious what is going on--sort of a trade off.
This comment has been hidden.
@HerrWert, which course would that be? Please send me a link. Thanks,
Needs random tests (and probably a bit more clear description)
Test Case Problem: test.assert_equals(longest_palindrome("abcdefghba"), 1) Are you sure this equals 1? Because I can see 'ab' both in 'abcdefghba' and in the reversed one.
First I fell for this too... the problem is that you are looking for the longest substring that can be found reversed in the original string. However, the task is to find the longest substring that is the same as its reverse: e.g. "bob" or "racecar" is the same if you read it from right-to-left (= palindrome); but "ab" is not (because it's "ba" when reversed).
Meh im stupid. I forgot the palindrome. Thanks anyway.
That is hilarious because I posted a similar issue
I'm having a problem when submitting in python. I pass all of the test cases, no problem but then when I go to submit I'm getting this:
'Process was terminated. It took longer than 6000ms to complete'
Anyone else experiencing this issue? I am given no other information... Should I post my code here?
I'm getting the exact same problem as well. And I can't figure out why.
Edit: Ended up looking at the solutions - I had overcomplicated my code so there were too many calculations being made when the answer was much simpler.
Same here. I thought my code just sucked that bad, haha.
Ends up my first solution was extremely convoluted. I solved it a simpler way and it worked just fine.
All my pre-test and submit tests pass, except the very last one: "Expected: 1, instead got: 2". Love the site but lack of hints takes a lot of fun out of it. How about allowing the user to reveal a test case (perhaps at the expense of points)?
Why not use
console.log()
to print the input? No need to waste points for something as simple as seeing the input.This comment has been hidden.
abba
,abcccba
,abcdefghhgfedcba
are valid palindrome strings. However,abcdefghba
is not a valid palindrome. I hope this helps.I fixed that test case. Please check now.
Looks good to me!
In "Your Test Cases": Test.assertEquals(longestPalindrome("zyabyz", 0, "Are you sure that is a palindrome?") should be: Test.assertEquals(longestPalindrome("zyabyz"), 1, "Are you sure that is a palindrome?") There is a parenthesis missing and the expected value is wrong, should be 1 rather then 0;
More tests including some random ones for the final submission might be good.
Actually, it should be
Test.assertNotEquals(longestPalindrome("zyabyz"), 6, "Are you sure that is a palindrome?")
Please check again. Thanks much!
Oh yeah, if it's "assertNotEquals" hehe. Yes, seems ok to me now.
So, what are you suggesting I do? Add another test case?
The
substring
in the description does refer toracecar
(notracecars
), and its length is7
. I shall make that amply clear now.This comment has been hidden.
Thanks for your feedback. Will provide helpful hints on the test cases.
Added an example test case that provides a helpful hint when it fails.
Thank you kgashok! I tried to mark the kata as ready now - hope that worked!
Add to description: if 0 return 0
Done! Thanks,
when you submit your final submission and the tests fail, there's no indication where it failed.
yes this is very annoying please fix asap
"abhgfedcba" should be 2, the test case is wrong as 1!
How do you figure? You say it is 2, but starting with which index?
This comment has been hidden.
But 'ab' and 'ba' must be contiguous for it to make a palindrome.
I agree with pinxue that test case "abcdefghba" should have answer 2, as "ab" and (reversed "ba") are palindromes--so are "ba" and (reversed "ab"). In fact, this test string contains two palindromes of length 2. If they were contiguous as you suggest ("abba"), the answer would be 4.
You seem to be saying that they can't be palindromes because they're not in the same position, as indicated by your question "starting with which index?", but that would mean "baa" should return 1 as well (instead of the correct answer, 2).
If there is some requirement as to contiguity or position, please spell it out in the description. Otherwise, the correct answer to the last test case in Final Submit should be 2.
My request for the "starting with index" was to better understand which substring
pinxue
was referring to. Here's my clarification of the test cases:"baa" -> the substring
"aa"
is a valid palindrome, and is of length 2. So, result is 2."abhgfedcba" -> there exists no substring (greater or equal to length 2) which is a valid palindrome. However, each letter by itself (of length 1) is a valid palindrome. So result is 1.
I hope this helps.
I enjoyed this one very much, so thank you.
You may want to clarify that none of the test cases actually include whitespace characters (as in the example sentence given in the kata description), or consider adding some that do.
Thank you for your suggestion. A test case with whitespace has been added.
Indicate whether the algorithm can be O(n^3) or if it must be, at worst, O(n^2). The O(n^2) situation warrants this kata being at most 5 kyu.
There is a O(n) solution.
this is my first exercise, thank you for your time and work.
so... I had a problem here.
All the tests passed when I run the tests, but the last one fail when I submit.
Running tests Test Passed: Value == 1 Test Passed: Value == 2 Test Passed: Value == 2 Test Passed: Value == 2 Test Passed: Value == 4 Test Passed: Value == 9 6 Passed 0 Failed 0 Errors
When I submit Test Passed: Value == 1 Test Passed: Value == 2 Test Passed: Value == 2 Test Passed: Value == 2 Test Passed: Value == 4 Test Passed: Value == 9 Expected: 1, instead got: 9 6 Passed 1 Failed 0 Errors Process took 74ms to complete
What is the problem?
Hard to tell only based on Passed/Failed report. The tests and final submission often use different tests, with the final submission ones being more extensive. So you most likely have a problem with you algorithm that is not apparent in the simpler tests.
(Just noticed your comment is from 8 months ago, but I'm posting the reply anyway lol)
I have the same problem
This comment has been hidden.
This comment has been hidden.
Typo in JavaScript:
longestPalidrome
should belongestPalindrome
(missingn
).Fixed: thanks bkaes :)!
Marking this as resolved.
JS and Ruby translations submitted, if you are interested :)
To me, this test seems wrong:
test.assert_equals(longest_palindrome("abcdefghba"), 0)
The right answer should be 1, consistent with
test.assert_equals(longest_palindrome("a"), 1)
The only case when the function should return 0, I think, is when the string is empty.
Agreed, fixed it.
By the way, adding a test to check that the function returns 0 for empty string should add fun, I think. :)
Done!
You've missed a closing parenthesis there, so it doesn't compile. :)
And by the way I meant submit test cases, more than example test cases. :)
Oops! Fixed it now. I am surprised how the "Re-publish" did not flag this. Oh well.
Yeah, it's good now, thanks.
It looks like "Publish" does not check the example test cases at all, probably assuming they could be consciously broken from the beginning to be fixed by the solver.
Can you please explain why it is 1 ?
test.assert_equals(longest_palindrome("abcdefghba"), 1)
Do you want to say that middle character "e" is palindrom with length of 1? If so, I don't get it. Makes no sense for me... Am I missing something?
https://en.wikipedia.org/wiki/Palindrome
A palindrome is a sequence of letter, numbers, etc that reads the same forwards as it does backwards. Therefore a 1 letter string can be said to be a "palindrome" because it reads the same if all the letters are reversed (in this case just one letter). From this we can deduct that any string will contain, at a minimum, a palindrome with a length of 1.
The tests should go the other way around.
test.assert_equals(longest_palindrome("a"), 1)
instead of
test.assert_equals(1, longest_palindrome("a"))
othewise when test fails it prints, for example
1 should equal 0
while it should print
0 should equal 1
Swapped it out, as suggested. Thanks,
Thanks!