0

I'm trying to create a function to find the longest segment within a given list t, which satisfies two conditions:

  1. The last number of the segment has to be equal or greater than the first number of the segment.

  2. Difference between the last number and the first number of the segment has to be equal or less than a given integer x.

I'm able to create a working piece of code, but it is too slow. I can't come up with a solution that would not utilize 'nested for-loops'.

The algorithm should work with lists up to 10^5 integers, each integer random from 1 <= x <= 10^9.

def find(t: list, x: int):
    n = len(t)
    max_len = 0

    for i in range(n):
        for j in range(i, n):
            if t[j] >= t[i] and t[j] - t[i] <= x:
                max_len = max(max_len, j - i + 1)

    return max_len

if __name__ == "__main__":
    print(find([1, 4, 6], 1)) # 1
    print(find([1, 4, 6], 10)) # 3
    print(find([4, 1, 10, 5, 14], 1)) # 4
    print(find([4, 1, 10, 5, 14], 10)) # 5
    print(find([9, 8, 7, 6, 5, 4, 3, 2, 1], 100)) # 1
Stef
  • 13,242
  • 2
  • 17
  • 28
poser
  • 45
  • 4
  • Is this online somewhere for testing? – Kelly Bundy Mar 01 '23 at 14:04
  • The values are required to be all integers, correct? Can `x` be expected to be small compared to the number of elements? – Karl Knechtel Mar 01 '23 at 14:43
  • @KellyBundy why would that matter? We are capable of doing our own performance testing and big-O analysis. The question is clearly about improving performance, not about satsifying a specific online tester. – Karl Knechtel Mar 01 '23 at 14:44
  • 2
    @KarlKnechtel I'd find that convenient. Also, often people leave out details or misrepresent something, so it often helps to see the original full specification. – Kelly Bundy Mar 01 '23 at 14:53
  • 1
    *"I'm able to create a working piece of code, but it is too slow. I can't come up with a solution that would not utilize 'nested for-loops'."* You will find a big hint in the answer to this related question: [What is Sliding Window Algorithm? Examples?](https://stackoverflow.com/a/56822591/3080723). Note that "sliding window" is the name of several unrelated things in computing, which is why I've linked to that specific answer and not to the other answers of that question or to a wikipedia article. – Stef Mar 01 '23 at 15:30
  • Are the elements unique? – SomeDude Mar 01 '23 at 15:55
  • 1
    @KellyBundy That would suggest that either you're still asleep or I've completely misread the question! – Stef Mar 01 '23 at 16:06
  • @KellyBundy Thanks for the gratuitous attack, I guess? – Stef Mar 05 '23 at 14:50
  • @KellyBundy I linked that answer because "sliding window" is an umbrella term that is used to talk about lots of different algorithms, including anything that looks like a convolution, and that makes it hard to find an explanation about sliding window algorithms by searching for this term. – Stef Mar 05 '23 at 14:51
  • @KellyBundy This answer is the only one I've found on all of StackOverflow that's about sliding-window algorithms as related to solving problems of the form "find the maximum substring that has some property", as opposed to sliding-window as in a convolution. It doesn't help that convolutional neural networks are superpopular these days, and flood the results of any search for sliding window. If you have found a better source that explains sliding window algorithms, I'm interested. Even wikipedia sucks in that regards. – Stef Mar 05 '23 at 14:51
  • @KellyBundy I actually haven't taken the time to read the question again and think about the problem since march 1, when I posted my last comment in which I stated that I might have misread the question. I had bookmarked this page so I could look at it again, because it's fun. But these kinds of comments don't make it fun at all. – Stef Mar 05 '23 at 14:54
  • @KellyBundy The article does begin by talking about "sliding window problems", which I agree is not an awesome term, but then they define that term with "a sliding window problem is a problem that can be solved with a sliding window algorithm". It makes sense to call that a property of the problem, just like articles about dynamic programming talk about the "optimal substructure" property of a problem, a property which is necessary for the existence of a dynamic programming algorithm to solve that problem. It's all a bit loosely defined, but makes sense. – Stef Mar 05 '23 at 15:37
  • @KellyBundy Looking at the questions under that tag, there appears to be a variety of questions, related to all meanings of sliding-window – Stef Mar 05 '23 at 16:07

1 Answers1

2

O(n log n) solution: Visit the values in increasing order, considering them as right endpoint. Keep the still relevant possible left endpoints in a monoqueue of increasing values and increasing indices. A value stops being a left endpoint candidate when

  • it becomes too small (for the current value and thus also for all remaining right endpoint candidates, as they are only getting bigger) or
  • its index is larger than the current value's index (because then the current value/index will always be a better left endpoint candidate for the remaining right endpoint candidates).
from collections import deque

def find(t: list, x: int):
    IV = deque()
    result = 1
    for i, v in sorted(enumerate(t), key=lambda e: e[1]):
        while IV and IV[0][1] < v - x:
            IV.popleft()
        if IV:
            result = max(result, i - IV[0][0] + 1)
        while IV and IV[-1][0] > i:
            IV.pop()
        IV.append((i, v))
    return result

Attempt This Online!

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65