HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

One element only subarray max length

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lengthonemaxelementonlysubarray

Problem

Task description


You are given a list and an item, find the length of the longest consecutive subsequence of the list containing only the item.

Testcases

[1, 1, 2, 3] 1 -> 2
[1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6] 0 -> 3


This code is pretty readable in my opinion but I fear that the \$O(N^2)\$ time complexity is sub-optimal.

def subsequences(arr)
  ((0...arr.length).to_a)
    .repeated_permutation(2)
    .select {|start, finish| finish >= start}
    .collect {|start, finish| arr[start..finish] }
end 

def longest_item_only_subsequence_len(arr, item)
   subsequences(arr)
     .select {|seq| seq.all? {|i| i == item} }
     .max_by(&:length)
     .length
end

p subsequences([1, 2, 3])
p longest_item_only_subsequence_len([1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6], 0)

Solution

Yes, chunk is the way to go. I'd write it differently, though, using a list-comphehension approach (in Ruby: map+if+compact. Or with a custom method.) and taking in account the edge case (no elements item in the array):

def longest_item_only_subsequence_len(xs, item)
  xs.chunk(&:itself).map { |y, ys| ys.size if y == item }.compact.max || 0
end

Code Snippets

def longest_item_only_subsequence_len(xs, item)
  xs.chunk(&:itself).map { |y, ys| ys.size if y == item }.compact.max || 0
end

Context

StackExchange Code Review Q#101640, answer score: 4

Revisions (0)

No revisions yet.