Skip to content

Instantly share code, notes, and snippets.

@burkestar
Last active May 20, 2016 12:30
Show Gist options
  • Select an option

  • Save burkestar/5d429f515a9542279d5cdd58cb735cf5 to your computer and use it in GitHub Desktop.

Select an option

Save burkestar/5d429f515a9542279d5cdd58cb735cf5 to your computer and use it in GitHub Desktop.
# Finds the longest streak and the current streak within a sequence.
# The sequence could correspond to consecutive days of Github commit history.
# The assumptions is that it is ordered chronologically so the current streak is computed from the tail end of the sequence.
# reduce maintains the state as a tuple consisting of (longest streak count, current streak count)
# The int(bool(y)) trick is to convert a numeric into a binary 0 or 1 which will determine whether or not the current streak should continue.
# Time complexity: O(n) since reduce will traverse each item in the sequence exactly once.
# Space complexity: O(n) + k to store the original sequence plus the additional state tuple that propagates through reduce.
data = [0, 2, 4, 6, 4, 32, 24, 4, 4, 5, 0, 2, 3, 4, 0, 0, 0, 0, 2, 0, 0, 4, 7, 9]
longest, current = reduce(lambda state, y: (max(state[0], state[1] + 1 if state[1] and y else int(bool(y))), state[1] + 1 if state[1] and y else int(bool(y))), data, (0, 0))
# returns: (9, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment