cronenberg's blog

By cronenberg, history, 7 years ago, In English

this problem was asked in the last week of code of hackerrank, I am having a hard time understanding the editorial can anyone help me with it?

  • Vote: I like it
  • -1
  • Vote: I do not like it

| Write comment?
»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

There are 3 cases for each query:

  1. X =  = Y or both of X, Y are not presented in array — all segments are good for us — it is N * (N - 1) / 2.

  2. Only one of X or Y is not presented. Let's X is presented and Y not. So you need to calculate number of segments where frequency(l, r, X) = 0.
    It's obvious that these segments placed between positions of X (we can imagine fictive X position before start of array and after it's end).
    If there D elements between two positions of X — there are D * (D + 1) / 2 segments with freq(x) = 0 (any pair of these elements).
    We can precalculate this value for every presented value with total complexity O(N).

  3. Both X and Y are presented in array. Let's imagine two arrays of length N prefX[] and prefY[]: prefX[i] is number of X on segment [1..i] (prefY[i] is the same for Y).
    So when segment [l..r] contains equal number of X and Y?
    When prefX[r] - prefX[l - 1] =  = prefY[r] - prefY[l - 1] — simply calculates number of X and Y on the segment.
    But we can rewrite it: prefY[r] - prefX[r] =  = prefY[l - 1] - prefX[l - 1].
    If we have a lot of time — we can calculate all differences in O(N) per query and calculate frequency of each difference (remember about prefY[0] - prefX[0] =  = 0 — there aren't any X or Y before array).
    For some difference D with frequency freq[D] we should add to answer freq[D] * (freq[D] - 1) / 2 — each pair of indexes, but not the same.
    Observation: difference is changed only when we meet X or Y in the array.
    So we can iterate over all positions of X and Y in the sorted order (it can be done with 'merge' technique from mergesort in O(freq(X) + freq(Y)) with O(N) preprocessing positions of all elements.
    At each position we change prefX or prefY, so current difference D = prefY - prefX is changed too.
    After that we can update answer on the spot — we need add to answer freq[D] before updating it with current index (we add to answer all segments with end at this index).
    Or we can do second cycle and add our formula value for each difference that we meet in first time.
    Anyway, we do it with O(freq(X) + freq(Y)) complexity for any pair (X, Y).
    It can be easily proved that total complexity for each possible pair (X, Y) when both are presented in the array is O(N2).
    So we have solution with O(Q + N2) complexity.