-1

I have been studying divide-and-conquer for a while, and am now looking into the following problem:

Given a permutation P of length N, count the number of good segments. Note that a sequence A of N integers is called a permutation of length N if:

    1≤ Ai ≤ N for all 1 ≤ i ≤ N, and Ai != Aj for all 1 ≤ i != j ≤ N.

A continuous segment [l, r] of a permutation P is good if the value of (Pl, Pl+1, ..., Pr) is also continuous. That is, if we collect Pl, Pl+1, ..., Pr into a new list B and sort it, then this will hold:

    B1 = B2−1, B2 = B3−1, ..., Bi-1 = Bi−1, ..., B|B|−1 = B|B|−1.

For example, in the permutation [3, 2, 4, 5], there are 8 good segments:

    [3], [2], [4], [5], [3,2], [4,5], [3,2,4], and [3,2,4,5]

I analysed several cases when combining two small divided arrays, but I cannot think of a strategy that can detect good segments that cross two separate arrays in O(N) time.

How can this be done?

Community
  • 1
  • 1
Dennis
  • 93
  • 11

1 Answers1

1

Personally I don't think it is possible to apply divide-and-conquer in efficient way here.

You need to inspect O(n^2) substrings of a given permutation. You may apply divide-and-conquer for example by dividing the array into 2 halves (left and right), inspect all substrings starting in the left half and ending in the right half, then call left and right halves recursively. This is going to give:

n/2 * n/2 = (n/2)^2 = (n^2)/4 substrings on level 1

n/4 * n/4 + n/4 * n/4 = 2 * (n/4)^2 = (n^2)/8 substrings on level 2

n/8 * n/8 + n/8 * n/8 + n/8 * n/8 + n/8 * n/8 = 4 * (n/8)^2 = (n^2)/16 substrings on level 3, and so on

This asymptotically yields O(n^2 * log n) substrings to be analyzed, worse than O(n^2) substrings if we just process them iteratively

For the number of subproblems larger than 2, things are not better: if we split into 3, complexity is O(n^2 * log3n), and so on

mangusta
  • 3,470
  • 5
  • 24
  • 47