GomerDoGo's blog

By GomerDoGo, history, 3 weeks ago, In English

So, I was sleeping and this problem just came to me in a dream:

Given an array a and an array b, we need to split a into contiguous subsegments and for each subsegment assign 1/0 — whether we reverse it or not. The question: can we determine if it's possible to obtain b from a?

So far I only know how to solve it in O(n²), but there's clearly a better way, help pls

  • Vote: I like it
  • +63
  • Vote: I do not like it

»
3 weeks ago, hide # |
 
Vote: I like it +11 Vote: I do not like it

hi , so i dreamt about the solution today in a nap ...

there was a fat horse who kept saying use 2 pointers+dp

»
3 weeks ago, hide # |
 
Vote: I like it +8 Vote: I do not like it

This is a very interesting problem!

I believe a solution can be found with DP[i] = whether solution exists up to position i, while only transitioning the shortest possible reversed interval and the shortest possible non-reversed interval from each position

If the next interval in any existing solution is not reversed and has length m, it can be partitioned into m intervals of length 1 each, so we will find it by repeatedly taking the shortest possible non-reversed interval

If the next interval in any existing solution is reversed, it gets more complicated. Suppose the shortest reversed interval we can take is [i, r1] and an existing solution has the next interval as [i, r2]. We can show that:

  • if [i, r1] does not cover the "center" of [i, r2] then a[i, r2] = S+T+S for some strings S and T and a[i, r1] = S, and we can still reach r2 by taking T next then S again
  • if [i, r1] does cover the "center" of [i, r2] then [i, r1] is not actually the shortest possible reversed interval (the symmetry of the center of [i, r2] is mirrored within [i, r1])

The shortest possible reversed interval from each position can be found in n*log(n) time by finding the largest possible interval from each possible center point with hashing + binary search, then applying sweepline

  • »
    »
    3 weeks ago, hide # ^ |
     
    Vote: I like it +10 Vote: I do not like it

    This is beautiful! Thank you a lot

    And if you are interested, in the Russian version of this post a guy proposed another solution:

    translation
»
3 weeks ago, hide # |
 
Vote: I like it -8 Vote: I do not like it

Probably related to this leetcode problem: https://leetcode.com/problems/scramble-string/description/.