Time limit exceeded (Ruby)


  • 0
    J

    Can someone help me find out why bellowing code got timeout? Thanks!

    def ladder_length(from, to, dict)
        queue = Queue.new
        queue << from
        level_queue = Queue.new
        level_queue << 1
        visited = {from => true}
    
        until queue.empty?
          word = queue.shift
          l = level_queue.shift
          (0..word.size-1).each do |i|
            ('a'..'z').each do |c|
              if word[i] != c
                word_copy = word.dup
                word_copy[i] = c
                if word_copy == to
                  return l + 1
                end
                if dict.include?(word_copy) && !visited[word_copy]
                  queue << word_copy
                  level_queue << l + 1
                  visited[word_copy] = true
                end
              end
            end
          end
        end
        0
    end

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.