Singly Linked List - Problem

Implement a singly linked list data structure with the following operations:

  • Insert at head: Add a new node at the beginning
  • Insert at tail: Add a new node at the end
  • Insert at position: Add a new node at a specific index
  • Delete by value: Remove the first node with given value
  • Search: Find if a value exists in the list
  • Display: Return all values as an array

For this problem, you'll implement the insert_head operation. Given an array representing the current linked list and a value to insert, return the array representation after inserting the value at the head.

Input & Output

Example 1 — Basic Insertion
$ Input: list = [2,3,4], value = 1
Output: [1,2,3,4]
💡 Note: Insert 1 at the head: the new list becomes [1,2,3,4] with 1 at the front
Example 2 — Empty List
$ Input: list = [], value = 5
Output: [5]
💡 Note: Inserting 5 into an empty list results in [5]
Example 3 — Single Element
$ Input: list = [10], value = 7
Output: [7,10]
💡 Note: Insert 7 at head of [10] gives [7,10]

Constraints

  • 0 ≤ list.length ≤ 103
  • -103 ≤ list[i] ≤ 103
  • -103 ≤ value ≤ 103

Visualization

Tap to expand
Singly Linked List - Head InsertionINPUTOriginal List:234New Value:1Insert at head positionALGORITHM1Create new array size n+12Place new value at index 03Copy original elements right4Return new arrayTime: O(n) - copy all elementsSpace: O(n) - new array neededRESULTNew List:1234Array: [1,2,3,4]Successfully inserted 1 at headOriginal elements shifted rightKey Insight:In array representation of linked lists, inserting at head requires creatinga new array with the new element first, followed by all existing elements.TutorialsPoint - Singly Linked List | Head Insertion
Asked in
Google 25 Amazon 30 Microsoft 20 Apple 15
28.5K Views
High Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen