Skip to the code
cf.
+10 XP

#248 Two-Ended Playlist

easy

A music app's queue lets you add a track to play next (the front) or last (the back), and remove from either end. Write a class Playlist backed by a doubly linked list so every call is O(1):

  • pushFront(track) and pushBack(track) add a track id at that end.
  • popFront() and popBack() remove and return the track at that end, or -1 if the playlist is empty.
  • peekFront() and peekBack() return the track at that end without removing it, or -1 if empty.
  • size() returns the number of tracks.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new Playlist(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["Playlist","pushBack","pushBack","pushFront","peekFront","peekBack","popBack","size"]
[[],[5],[8],[2],[],[],[],[]]
Output: [null,null,null,null,2,8,8,2]

The playlist becomes 2, 5, 8. The front is 2, the back is 8, and removing the back leaves 2 tracks.

Example 2

Input: ["Playlist","popFront","popBack","peekFront","size"]
[[],[],[],[],[]]
Output: [null,-1,-1,-1,0]

Every read on an empty playlist gives -1, and its size is 0.

Constraints

  • 1 <= track <= 1000
  • At most 1000 calls in total.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).