[Community Puzzle] Tree Paths

Oh I see. In that case you may have to test in the contribution view. If required, we can discuss by PM here.

i solved the problem with validator 4. with help from 5DN1L.

the problem is the missing last newline in the input. it caused my bash code to not handle the last line. validator 4 is the only test case where the target key is in the last line. i modified my code so it appends a last newline and now validator 4 works.

what really confused me was: when testing using the custom test feature in the codingame ide the input does have a last newline. so when i tested all possible target nodes for test case 4 in the custom test feature my code worked flawlessly. but in the validation the input had no last newline so my code did not work for validator 4.

this is a bit aggravating but i guess such is life for the bash hacker.

more details and background info:

most command line tools expect a line to be terminated by a newline. some tools behave differently if a line is not terminated by a newline.

the typical bash script loop to read lines from stdin

while read line ; do
    something with "$line"
done

will not handle the last line if the last line does not have a terminating newline.

demo

printf '1\n2\n3' | while read line ; do
    echo $line
done

will print

1
2

the third line is not handled because it lacks a terminating newline.

the thing is: read still read the line. so the contents of the variable $line is 3. but since it did not encounter a newline and instead encountered an ā€œend of inputā€ it returned an ā€œerrorā€ which caused the while loop to exit without executing the body. so the last line is not handled.

to workaround this you can do

while read line || [ -n "$line" ] ; do

or

grep "" | while read line ; do

read here for more info

bash - Shell script read missing last line - Stack Overflow

2 Likes

Good easy puzzle.
But looks like the first parameter N is unnecessary.

It allows you to do it with arrays instead of hashmaps, which makes it easier for some languages.

Iā€™m somehow passing all test cases, and all custom test cases listed here, and failing validator 1 and 2 when submitting.

Any hints on what validator 1/2 are and why they may fail while 3, 4 and 5 pass?

Not sure, but you may try to create similar custom cases to test your code. That should be relatively easy because the number of possibilities is limited. (Number of nodes = 3 and the number of nodes with two children = 1 for tests/validators 1 and 2.)

1 Like

Thanks for the response.
I had made an assumption about the root of the tree that didnā€™t hold true.
Solved it by reversing the solution.