NOV18 - Problem Discussion

copy paste

Hey guys!!

Finally after 10 tiring days the A̶u̶g̶u̶s̶t̶ November long concludes. Lets share our approaches for the problems here while editorials for problems come out (at this moment none n̶o̶t̶ ̶a̶l̶l̶ of them are out)? Got any interesting approach which you cant wait to share? The wait is over :slight_smile:

So, which was your favourite problem? I had best time solving ̶I̶n̶t̶e̶r̶a̶c̶t̶i̶v̶e̶ ̶M̶a̶t̶r̶i̶x̶ ̶:̶)̶.̶ MAGICHF2 ̶T̶h̶e̶ ̶p̶r̶i̶n̶c̶e̶s̶s̶ ̶g̶a̶v̶e̶ ̶m̶e̶ ̶a̶ ̶r̶u̶n̶ ̶f̶o̶r̶ ̶m̶y̶ ̶s̶c̶o̶r̶e̶ ̶x̶D̶ ̶-̶ ̶s̶o̶ ̶I̶ ̶l̶e̶t̶ ̶h̶e̶r̶ ̶s̶t̶a̶y̶ ̶w̶i̶t̶h̶ ̶d̶r̶a̶g̶o̶n̶s̶ ̶a̶n̶d̶ ̶b̶e̶ ̶b̶y̶ ̶h̶e̶r̶s̶e̶l̶f̶ ̶t̶h̶e̶n̶ :stuck_out_tongue:

But on a serious note, anyone who was able to MAXDTREE s̶a̶v̶e̶ ̶t̶h̶e̶ ̶p̶r̶i̶n̶c̶e̶s̶s̶ ̶(̶o̶r̶ ̶p̶r̶i̶n̶c̶e̶.̶.̶.̶? :p). I kept on getting TLE W̶A̶ for larger TCs, so I appreciate any approaches for it :slight_smile:

P.S. - If someone can write something on interpolation (s)he is most welcomed. I invite @gorre_morre and @algmyr for this task. (:frowning: Tagging here don’t send any notification.) I derived some required equations for CHEFEQUA, didn’t check the correctness of those equations because I knew even I these are correct then time left for the contest in insufficient to implement those.

Let the discussion begin!

/copy paste


What can be even faster way for this problem “HMAPPY1”

Problem Link: CodeChef: Practical coding for everyone

My Solution: CodeChef: Practical coding for everyone

my solution was only able to get me partial points…

Can someone share his/her approach of binary string? It has really weak test cases, my brute in PYPY passed with a fast IO. In the test cases, there was a large string only, so without inserting it in the trie, one could solve it. But can someone share an approach which runs for large and strong test cases.?

1. For HMAPPY1:
I used Segment Tree. Though, it can be done with Bruteforce on Strings. Here is my


**2. For [GMEDIAN][3]:**
I used combinatorics approach as the naive submission had complexity O(2^n) which can be seen as a pattern. Here is my 


3. For MAGICHF2:
This was a simple problem. All you needed is a correct direction of moves and evade some edge cases Here is my


**4. For [BINSTR][7]:**
I used Trie with Intervals for this problem. The main issue with this problem is different lengths with larger differences between max length and second max length and the larger number of zeros to be appended which I saved beforehand to prevent again and again traversal. Here is my 


If you feel like I should comment the code, or you have any queries in the code, you are free to ping me here :slight_smile:

1 Like

Please suggest some test case for which my HMAPPY1 solution should fail, because I am only able to pass few test cases, and others are showing wrong answer.I tried all the possible combination of arrays but still many test cases showing wrong answer.

Problem Link

My solution

My solution to HMAPPY1… segment tree not used… is based completely on analysis

first find 2 max size substring and store their first and last pointer and when shift queries come you just move 4 points and for length query you just need to check size of both substring both query thake O(1) time

Its simple observation you for making odd length subset you have 2^(n-1) possible way i proved that with equation (l+r) C (l) way to choose elements in array at (l+1) position where (l+r+1) = n

Now for even length we need to check frequency of number and after some observations you can find solutions with O(n²) so total time complexity O(n²)

If N is even than we need to divide N like after devide N is two part one part still can divide by 2
But for odd we need to add one into it
And after logN/K iteration you can find its probability.

"CHEF and Eq "
First i tried with Gaussian elimination in O( n³ ) but after reading some papers i can make in O(n²)
Its known as vandermonde matrix.
And i read about FFT i think that it will be solutions of it
May be using MOD root of unity.
I can’t solve it for 100 point.

O( N²) for more information

" MaxDigit "

For subtask 1 we just need to know how many paths are passing from node 1 in s using dfs an after than remove node from distance 3 and ( Children of root C 2 ) from ans…

I didn’t paste partially point solutions you can check

For prime tree and Chef and recipe i used brute force approach for partially point
I got TLE in BinXor


The test cases for Binary Strings were very weak, I have seen many PYPY solutions where just brute force was applied and they got AC. It just kills the main motive behind the problem and a language advantage is the last thing I want to see on Codechef. I myself was not able to solve the problem and seeing so many people get AC using only brute force is saddening :frowning:

I am eagerly waiting for Editorial of CHEFEQUA , RECIPIES, and MAXDTREE. I was only able to grab partial points.

RECIPES: These type of Half-second question are really interesting. (CPCOMP) Last time. One can definitely relate merging of elements. @bciobanu or @gorre_morre anyone else who could enlighten about variants of these kinds of problems would be help to all. I am really eager to know different approach to solve such merging question.

CHEFEQUA: A Math-Mamoth I would say. One could easily figure out 20 point solution using Vandermonde Matrix to solve Linear System of Equation. After some more efforts one could relate it with FFT and Interpolation. The giant Task lies in connecting it question. I spent a lot of time going through different articles and Tutorial about FFT and Interpolation. Unfortunately, I couldn’t figure out the solution for question. @taran_1407 expecting a gem from you again.

MAXDTREE: One can check the length of patterns with occurrence of 2 using program to generate series and easily deduce that pattern for 2 exist for all, but length 3. I am totally blank about that 100pt approach. Waiting for editorials.

An awesome contest, I would say. Learnt a lot ( though couldn’t implement everything :stuck_out_tongue: ).


Hey Guys , Can anyone help me with BinaryStrings , I tried making a TRIE and taking maximum of the input length of the string and padding all others with same 0s to make the strings equal , any query string with length greater than this , I took a substring of the the appropriate length (max length that is ), i searched in TRIE as usual and each node with indices which pass through that number were stored , I calculated the one in range linearly , It passed most of the cases but TLED in(5,7,8,14)My solution :-CodeChef: Practical coding for everyone
Can someone please suggest why this is so are the input strings too big such that you cant pad everyother string or is it due to the way i search in Ingervals
Side Note :- Also there was Sigsegv before for the cases not TLED , did it exceed memory Requirement in anyway ?Any help is appreciated! Thankyou :D:D

1 Like


I used Gauss Elimination + Bitmasks. My Soln


I used O(n^3) to find the inverse of a matrix and fetch 5pts. My Soln


My approach was to count Bad Sequences. Only matrices with even length(2*n) and different element on n and n+1 position are bad. My Solns O(n*logn) O(n^2*logn) . I recommend reading O(n^2*logn) first.
Let Sequence Length = 2*n
GMEDIAN 100 pts = 2^n - (Even length elements with nth , n+1th element are different.)
Run a for loop fixing nth element.
Let no of elements less than x.X be cnt. And no of elements less than and equal x.X be cnt+x.Y. No of ways different first half = C(cnt+x.X,n) - C(cnt,n)
nth element x.X = All sequences with nth element <= x.X - All sequences with nth element < x.X


I first made a hypothesis that all no which contains only 2 as digits are present. Running it offline gave me 222. Rest all no up to 2222222222 (10 digits) were present in this recurrence.
I changed the hypothesis in All no of form 222…2222 are present in this recurrence except 222. My Soln (20 pts)


My code is of 415 lines uncommented. I will keep job of explaining soln of this for editorials and other community members.

Click to view

TRIE + 2 segment trees +two overlap functions (although one is sufficient) + 1bf fn + 1 soln fn + 1 search fn + 2dfs fn(although 1 is sufficient) + 2 debug fn + string to int conversion + int to string conversion.

Chef Vijju Corner -#

Click to view

@vijju123 named my trick of checking upto 2222222222(10 digits) and assuming rest to be true as -

Click to view

alt text



My Solution (100pts)

Since the sequence C is not really restricted to have only N elements, I made a generating function for it. What you get is:

\displaystyle C_0 + C_1x + C_2x^2 \ldots = \sum_{i=0}^{N-1} B_i(1 + A_ix + A_i^2x^2 + \ldots) = \sum_{i=0}^{N-1} \frac{B_i}{1-A_ix}

\displaystyle \text{Now let } Q(x) = \prod_{i=0}^{N-1}(1-A_ix)

If I multiply Q to both sides of this, on the right I get a polynomial of degree N-1 i.e. N coeffients.

Since the first N coefficients of the product depend only on the first N coefficients of the 2 polynomials being multiplied, I can write the right side as \displaystyle \frac{P(x)}{Q(x)} where P(x) = The first N coefficients of \displaystyle (C_0 + C_1x + C_2x^2 \ldots + C_{N-1}x^{N-1})Q(x)

\displaystyle \therefore \frac{P(x)}{(1-A_1x)(1-A_2x)\ldots(1-A_{N-1}x)} = \frac{B_1}{1-A_1x} + \frac{B_2}{1-A_2x} \ldots \frac{B_{N-1}}{1-A_{N-1}x}

This is a partial fraction decomposition and the solution is given by \displaystyle B_i = -A_i\frac{P\left(\frac{1}{A_i}\right)}{Q'\left(\frac{1}{A_i}\right)} where Q' is the derivative of Q (cover up method).

If we further let P^*(x) = x^{N-1}P\left(\frac{1}{x}\right) i.e. the polynomial we get by reversing the coefficient list of P and similarly Q^*(x) = -x^{N-1}Q'(\frac{1}{x}) we get

\displaystyle B_i = A_i\frac{P^*(A_i)}{Q^*(A_i)}

We can find out the values of P^* and Q^* at any N points in O(N\log^2 N) using the algorithm described here.

An example in case anyone doesn’t get it. I’ll be using the sample test case for this.

Q(x) = (1-x)(1-2x)(1-3x) = 1-6x+11x^2-6x^3

P(x) = \text{First 3 coefficients of } (3+6x+14x^2)(1-6x+11x^2-6x^3) = 3 - 12x + 11x^2

P^* (x) = 11-12x+3x^2

Q'(x) = -6 + 22x - 18x^2

Q^* (x) = 18 - 22x + 6x^2

\therefore B_0, B_1, B_2 = \text{value of } \displaystyle x\frac{11-12x+3x^2}{18-22x+6x^2} \text{ at } x=1,2,3 \text{ respectively.}


How the heck do you solve RECIPES? The only solution I know is checking if there’s a subset XOR = 0, and for this I check for each bitset if there’s a subset not having it that XOR is equal to it. Performed Gaussian Elimination, however, there are N equations and K variables maximally, which bring a query’s complexity to O(NK^2), and this of course TLE out even on subtask 2. So how did you guys Gauss? What were the equations, and what were the variables?

I used a double ended queue for solving HMAPPY1, by storing count of consecutive 1’s and 0’s. Like for case: 1 1 0 0 0 1 1 deque contains: 2 -2 2. I found that max value after rotation depends on front and rear too.

Link to my solution : CodeChef: Practical coding for everyone

Can anyone tell what I could do to improve my solution to BINSTR (CodeChef: Practical coding for everyone). I’ve implemented a radix tree and for input strings of different lengths, I’m padding the shorter strings with 0’s initially.
My solution gives TLE on tasls 5, 7, 8 but runs in <= 0.08 seconds on all the other.

1 Like

Noobie here: Please explain the 1st problem CHFTIRED

About CHEFEQUA, I think that @psaini72 solution is great. But here is what I did:

When I first saw the problem I recognized that the matrix in the problem is the transpose of something called a Vandermonde matrix, usually denoted V. This is a well known type of matrix and from some googling I found On the Inversion of Vandermonde Matrices pretty much telling me how to solve this problem. Note that the inversion formula for V^T contains V, which will essentially be just a multipoint evaluation of a polynomial at points A_0,A_1,…,A_{N-1}. So all I needed to do now was to implement a multipoint evaluator for polynomials.

My favorite source for FFT algorithms are these lecture notes. It shows how to reduce multipoint evaluation to polynomial modulu at a cost of O(N \log^2 N). After looking around I also found these lecture notes on how to implement polynomial modulu in O(N \log N) using convolution based on FFT or NTT. Later on I even found that someone had already implemented this specific algorithm in python. This implementation is probably pretty slow and there are some things that could be done differently so I made my own implementation in C++, still it should be pretty easy to rewrite the python code into a somewhat quick fully working C++ code if you just want to solve the problem.

Finally after getting accepted I noticed that I only got a running time of 2.3 s while some people got around 1.2 s, so I tried to speed up the algorithm. After playing around with the algorithm for a bit I noted that what slowed everything down was that I used 4 mod operations in the deepest part of my NTT. After some thinking/rewriting I was able to get it down to using a single mod operation, speeding up the algorithm significantly. Currently I’m pretty happy with my implementation, it is both pretty clean, readable and especially the NTT is noticeable quicker than most implementations I’ve seen. All in all I got it running in under <1.2 s. I could probably even get it under 1 s by reusing some calculations.

Can somebody suggest test cases for GMEDIAN on which my code is failing?

First I found the number of odd subsequeces by: 2^(N-1)

I have used following variables:
l=length of contiguous subsequence containing elements less than that number
r=length of contiguous subsequence containing elements more than that number
d=length of duplicate string

Then,I have choosen the duplicate subsequences containing of even length and then choosen equal elements from left and right side
EXP:{ C[l,0]C[r,0] + C[l,1]C[r,1] +...+ C[l,l]C[r,l] }X{ C[d,2]+C[d,4]+...+C[d,d OR d-1] }  
EXP:{              C[N-d,l]                          }X{        2^(d-1)-1                }
                BECAUSE: l+r = N-d

Then,I have choosen the duplicate subsequences containing of odd length and then choosen unequal elements from left and right side(by diff of 1)   
EXPR 1:{C[l,0]C[r,1] + C[l,1]C[r,2] +...+ C[l,l]C[r,l+1] }X{ C[d,3]+C[d,5]+...+C[d,d OR d-1] } 
EXPR 1:{                    C[N-d,l+1]                   }X{           2^(d-1)-d             }

EXPR 2:{C[l,1]C[r,0] + C[l,2]C[r,1] +...+ C[l,l-1]C[r,l] }X{ C[d,3]+C[d,5]+...+C[d,d OR d-1] }  
EXPR 2:{                   C[N-d,l-1]                    }X{           2^(d-1)-d             }


Here’s a test Case on which your program is failing.



1 2 2 2 2 3 3 3

The correct answer is 196 while your code outputs 192.