1

I am trying to solve frequent values using Segment Tree

This blog article uses a similar approach

I want to split a list into intervals as:

-1 -1 1 1 1 1 3 10 10 10 becomes (0, 2) (2, 6) (6, 7), (7, 10)

I have a code as:

g s = map (\x->(head x, length x)) . group . sort $ s

But it does not give the correct output.

Is it possible with frequent values too?

CDspace
  • 2,639
  • 18
  • 30
  • 36
Zubin Kadva
  • 593
  • 1
  • 4
  • 29

1 Answers1

5

I'd do it as

f = neighbors . prefixSums . counts
  where
    counts = map length . group . sort
    prefixSums = scanl (+) 0
    neighbors xs = zip xs (tail xs)

This starts by computing the counts of elements, so your (arbitrary permutation of) [-1, -1, 1, 1, 1, 1, 3, 10, 10, 10] becomes [2, 4, 1, 3].

Then, prefixSums computes the sums of prefixes, and so we get [0, 2, 6, 7, 10] for our running example.

To get the end result, we simply take the consecutive neighbors of this list.

Cactus
  • 27,075
  • 9
  • 69
  • 149