O(nlogn) Algorithm - Find three evenly spaced ones within binary string

前端 未结 30 2935
刺人心
刺人心 2020-11-28 00:07

I had this question on an Algorithms test yesterday, and I can\'t figure out the answer. It is driving me absolutely crazy, because it was worth about 40 points. I figure

30条回答
  •  遥遥无期
    2020-11-28 00:41

    # 
    def contains_evenly_spaced?(input)
      return false if input.size < 3
      one_indices = []
      input.each_with_index do |digit, index|
        next if digit == 0
        one_indices << index
      end
      return false if one_indices.size < 3
      previous_indexes = []
      one_indices.each do |index|
        if !previous_indexes.empty?
          previous_indexes.each do |previous_index|
            multiple = index - previous_index
            success_index = index + multiple
            return true if input[success_index] == 1
          end
        end
        previous_indexes << index
      end
      return false
    end
    # 
    
    def parse_input(input)
      input.chars.map { |c| c.to_i }
    end
    

    I'm having trouble with the worst-case scenarios with millions of digits. Fuzzing from /dev/urandom essentially gives you O(n), but I know the worst case is worse than that. I just can't tell how much worse. For small n, it's trivial to find inputs at around 3*n*log(n), but it's surprisingly hard to differentiate those from some other order of growth for this particular problem.

    Can anyone who was working on worst-case inputs generate a string with length greater than say, one hundred thousand?

提交回复
热议问题