Alternating polarity: hints, no solution
Medium · Two pointers
A waveform is stored as a list of non-zero integer samples. A mastering step needs the signal to swing back and forth, so it must rearrange the samples into a new list whose polarity alternates.
Rules: the new list starts with a positive sample when there is one. Positive samples keep their original relative order and so do negative samples. Take samples alternately, one positive then one negative, for as long as both kinds remain. When one kind is used up, put the rest of the other kind at the end in original order. Return the new list, leaving the input alone.
Examples
- Input
- samples = [3, -1, -2, 4, 5, -6]
- Output
- [3, -1, 4, -2, 5, -6]
- Note
- Positives 3, 4, 5 and negatives -1, -2, -6 interleave in order.
- Input
- samples = [-1, -2, 3]
- Output
- [3, -1, -2]
- Note
- There is one positive; the two negatives follow it in original order.
- Input
- samples = [-5]
- Output
- [-5]
- Note
- A single sample stays as it is.
Constraints
- 0 <= samples.length <= 500
- samples[i] is non-zero, -999 <= samples[i] <= 999
- Return a new list of the same length
Hint 1: a nudge
What do the positive samples need to keep, and what do the negative samples need to keep, independently of each other?
Unlock the full hints and timed practice with a pass
The second and third hints and the timed, runner-checked practice are part of a pass.