InterviewDB Question

Beat Notations - Parse and Validate Musical Rhythm Sequences

Question Details

Round 1 Coding

Problem

You are given a string representing a musical beat sequence using a notation where 'Q' = quarter note (1 beat), 'H' = half note (2 beats), 'E' = eighth note (0.5 beats), and 'R' = rest (1 beat). Given a measure length in beats, determine if a given sequence exactly fills one measure with no remainder.

python
def is_valid_measure(notation: str, beats_per_measure: int) -> bool:
    # notation: string of characters from {Q, H, E, R}

**Return** True if total beats == beats_per_measure exactly
    ...

def parse_beats(notation: str) -> float:

**Return** total beat count for the notation string
    ...

**Example**:
parse_beats("QQHQ")   ->  1+1+2+1 = 5.0
parse_beats("EEEE")   ->  0.5*4  = 2.0
parse_beats("HHRR")   ->  2+2+1+1 = 6.0

is_valid_measure("QQHQ", 4)  -> False  # 5 != 4
is_valid_measure("QQRR", 4)  -> True   # 1+1+1+1 = 4

Extension: Given a target measure length, generate all valid notation strings of length exactly n characters.

Follow-ups

  1. How would you handle invalid characters in the input string?
  2. Can you extend the notation to support dotted notes (e.g. 'Q.' = 1.5 beats)?
  3. How would you validate an entire song (list of measure strings) against a time signature?
  4. What parsing approach handles arbitrarily nested groupings (e.g. triplets)?

Full Details

Round 1 Coding

Problem

You are given a string representing a musical beat sequence using a notation where 'Q' = quarter note (1 beat), 'H' = half note (2 beats), 'E' = eighth note (0.5 beats), and 'R' = rest (1 beat). Given a measure length in beats, determine if a given sequence exactly fills one measure with no remainder.

python
def is_valid_measure(notation: str, beats_per_measure: int) -> bool:
    # notation: string of characters from {Q, H, E, R}

**Return** True if total beats == beats_per_measure exactly
    ...

def parse_beats(notation: str) -> float:

**Return** total beat count for the notation string
    ...

**Example**:
parse_beats("QQHQ")   ->  1+1+2+1 = 5.0
parse_beats("EEEE")   ->  0.5*4  = 2.0
parse_beats("HHRR")   ->  2+2+1+1 = 6.0

is_valid_measure("QQHQ", 4)  -> False  # 5 != 4
is_valid_measure("QQRR", 4)  -> True   # 1+1+1+1 = 4

Extension: Given a target measure length, generate all valid notation strings of length exactly n characters.

Follow-ups

  1. How would you handle invalid characters in the input string?
  2. Can you extend the notation to support dotted notes (e.g. 'Q.' = 1.5 beats)?
  3. How would you validate an entire song (list of measure strings) against a time signature?
  4. What parsing approach handles arbitrarily nested groupings (e.g. triplets)?
Free preview. Unlock all questions →

Topics

Coding Onsite Phone