Design Linked List

MediumLinked Listdesign

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Implement your own singly (or doubly) linked list of integers. Indices are 0-based. - MyLinkedList() creates an empty list. - get(index) returns the value at index, or -1 if index is not a valid position. - addAtHead(val) inserts val before the first element. - addAtTail(val) appends val after the last element. - addAtIndex(index, val) inserts val so that it ends up at position index. If index equals the length, this appends. If index is greater than the length, nothing happens. - deleteAtIndex(index) removes the element at index if that position exists; otherwise nothing happens. Do not use a built-in list type to hold the elements.

Examples

Input: ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"] [[],[4],[9],[1,6],[1],[1],[1]]
Output: [null,null,null,null,6,null,9]
The list goes 4 -> 4, 9 -> 4, 6, 9. Position 1 holds 6; after deleting it, position 1 holds 9.
Input: ["MyLinkedList","addAtIndex","addAtIndex","get","deleteAtIndex","get"] [[],[1,5],[0,2],[0],[3],[1]]
Output: [null,null,null,2,null,-1]
Index 1 is past the end of the empty list, so the first insert is ignored. Deleting index 3 and reading index 1 are both out of range.

Constraints

  • `0 <= index, val <= 1000`
  • At most 2000 calls in total.
  • Do not use a built-in linked list or array to store elements.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More design problems