0% found this document useful (0 votes)
27 views

Linked List Q&A

The document contains questions and answers about linked lists. Some key points: 1) To remove duplicates from an unsorted linked list, a hash table can be used to track duplicates. Without a buffer, the list can be sorted and then duplicates removed in NlogN time. 2) To find the kth to last element, two pointers can be used - place them k nodes apart and move one pointer until it reaches the end. 3) To delete a node where only that node is accessible, copy the next node's data over and delete the next node. 4) Problems covered include reversing lists, detecting cycles, merging sorted lists, moving elements around based on values, and more. Solutions generally

Uploaded by

Bobi Lip
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Linked List Q&A

The document contains questions and answers about linked lists. Some key points: 1) To remove duplicates from an unsorted linked list, a hash table can be used to track duplicates. Without a buffer, the list can be sorted and then duplicates removed in NlogN time. 2) To find the kth to last element, two pointers can be used - place them k nodes apart and move one pointer until it reaches the end. 3) To delete a node where only that node is accessible, copy the next node's data over and delete the next node. 4) Problems covered include reversing lists, detecting cycles, merging sorted lists, moving elements around based on values, and more. Solutions generally

Uploaded by

Bobi Lip
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Linked list

● Unlike an array, a linked list does not provide constant time access to a particular
"index" within the list. This means that if you'd like to find the Kth element in the list,
you will need to iterate through K elements.

Question
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP, How would you solve this problem if a temporary buffer is not allowed?

Answer
● In order to remove duplicates from a linked list, we need to be able to track
duplicates. A simple hash table will work well here.
● If we don't have a buffer ,and we can modify the list - we can sort it !, and than in
NlogN

Question
Implement an algorithm to find the kth to last element of a singly linked list.

Answer
We can use two pointers,pi and p2. We place them k nodes apart in the linked list by putting
p2 at the beginning and moving pi k nodes into the list.

Question
u given only access to the node we want to delete (not to the head) , Implement an algorithm
to delete a node

Answer
The solution is simply to copy the data from the next node over to the current node, and then
to delete the next node.

Question
Given a singly linked list, find middle of the linked list.

Answer
Traverse linked list using two pointers. Move one pointer by one and other pointer by two.

Question
Add 1 to a number represented as linked list

Answer
Below are the steps :
1. Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.
2. Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move
to the next node. Keep moving to the next node while there is a carry.
3. Reverse modified linked list and return head.
Question
reverse a list in place

Answer

public void reverse()


{
Node prev = null;
Node current = head;
Node next = null;

while(current != null)
{
next = current.next;
current.next = prev;

prev = current;
current = next;
}

head = prev;
}

Question
Write code to partition a linked list around a value x, such that all nodes less than x come
before all nodes greater than or equal to x.

Answer :
2 Options :
1. we can actually create two different linked lists: one for elements less than x, and one
for elements greater than or equal to x.We iterate through the linked list, inserting
elements into our before list or our after list. Once we reach the end of the linked list,
we merge the two lists.
2. Improvement: we can use only 1 linked list and insert element in the head or tail by
the value.

Question
Given two (singly) linked lists, determine if the two lists intersect. Return the
intersecting node. Note that the intersection is defined based on reference, not value. That
is, if the {k}th node of the first linked list is the exact same node (by reference) as the {j}th
node of the second linked list, then they are intersecting.

Answer :
We now have a multistep process.
● Run through each linked list to get the lengths and the tails.
● Compare the tails. If they are different (by reference, not by value), return
immediately. There is no intersection.
● Set two pointers to the start of each linked list.(On the longer linked list, advance its
pointer by the difference in lengths)
● Now, traverse on each linked list until the pointers are the same.
Question:
Given a singly linked list L0 -> L1 -> … -> Ln-1 -> Ln. Rearrange the nodes in the list so that
the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 …
You are required do this in-place without altering the nodes’ values.
Examples:
Input: 1 -> 2 -> 3 -> 4
Output: 1 -> 4 -> 2 -> 3

Answer
1) Find the middle point.
2) Split the linked list in two halves using found middle.
3) Reverse the second half.
4) Do alternate merge of first and second halves.

Time Complexity of this solution is O(n).

Question:
Write a function detectAndRemoveLoop() that checks whether a given Linked List contains
loop and if loop is present then removes the loop and returns true. if the list doesn’t contain
loop then returns false.

Answer
This method is also dependent on Floyd’s Cycle detection algorithm.
1) Detect Loop.
2) Count the number of nodes in loop. Let the count be {k}.
3) Fix one pointer to the head and another to {k -1}th node from head.
4) Move both pointers at the same pace, they will meet at loop starting node.
5) Get pointer to the last node of loop and make next of it as NULL.

Question:
We are given a linked list and positions m and n. We need to reverse the linked list from
position m to n. Examples:

Input : 10->20->30->40->50->60->70->NULL
m = 3, n = 6
Output : 10->20->60->50->40->30->70->NULL

Answer
● To reverse the linked list from position m to n, we find addresses of start and end
position of the sub linked list
● we unlink this part from the rest of the list .
● then reverse the unlinked sublist
● After reversal, we again attach the portion reversed to the main list.

Question:
Can we search in a sorted linked list in better than O(n) time?
Answer
The worst case search time for a sorted linked list is O(n) as we can only linearly traverse
the list and cannot skip nodes while searching.
The answer is Skip List. The idea is simple, we create multiple layers so that we can skip
some nodes. See the following example list with 16 nodes and two layers.

The upper layer works as an “express lane” which connects only main outer stations, and
the lower layer works as a “normal lane” which connects every station.

Suppose we want to search for 50, we start from first node of “express lane” and keep
moving on “express lane” till we find a node whose next is greater than 50. Once we find
such a node (30 is the node in following example) on “express lane”, we move to “normal
lane” using pointer from this node, and linearly search for 50 on “normal lane”.

What is the time complexity with two layers? The worst case time complexity is number of
nodes on “express lane” plus number of nodes in a segment (A segment is number of
“normal lane” nodes between two “express lane” nodes) of “normal lane”. So if we have {n}
nodes on “normal lane”, √n (square root of n) nodes on “express lane” and we equally divide the
“normal lane”, then there will be √n nodes in every segment of “normal lane” . √n is actually optimal
division with two layers. With this arrangement, the number of nodes traversed for a search will be
O(√n).
Therefore, with O(√n) extra space, we are able to reduce the time complexity to O(√n).

Question:
Given a linked list and a key in it, the task is to move all occurrences of given key to end of
linked list, keeping order of all other elements same.

Input : 1 -> 2 -> 2 -> 4 -> 3


key = 2
Output : 1 -> 4 -> 3 -> 2 -> 2

Input : 6 -> 6 -> 7 -> 6 -> 3 -> 10


key = 6
Output : 7 -> 3 -> 10 -> 6 -> 6 -> 6

Answer
1. Traverse the linked list and take a pointer at tail.
2. Now, check for the key and node->data, if they are equal, move the node to last-next,
else move Ahead.
Question:
Given K sorted linked lists of size N each, merge them and print the sorted output.

Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11

Output:
0->1->2->3->4->5->6->7->8->9->10->11

Answer
We already know that merging of two linked lists can be done in O(n) time and O(1) space .

The idea is to pair up K lists and merge each pair in linear time using O(1) space. After first
cycle, K/2 lists are left each of size 2*N. After second cycle, K/4 lists are left each of size 4*N
and so on. We repeat the procedure until we have only one list left.

Question:
Move all zeros to the front of the linked list
Given a linked list. the task is to move all 0’s to the front of the linked list. The order of all
other element except 0 should be same after rearrangement.

Input : 0 1 0 1 2 0 5 0 4 0
Output :0 0 0 0 0 1 1 2 5 4

Input :1 1 2 3 0 0 0
Output :0 0 0 1 1 2 3

Answer
An efficient solution is to traverse the linked list from second node. For every node with
0 value, we disconnect it from its current position and move the node to front.

Question: @@YONI
There are n people standing in a circle waiting to be executed. The counting out begins at
some point in the circle and proceeds around the circle in a fixed direction. In each step, a
certain number of people are skipped and the next person is executed. The elimination
proceeds around the circle (which is becoming smaller and smaller as the executed people
are removed), until only the last person remains, who is given freedom.

Given the total number of persons n and a number m which indicates that m-1 persons are
skipped and m-th person is killed in circle. The task is to choose the place in the initial circle
so that you are the last one remaining and so survive.
Examples:

Input : Length of circle : n = 4


Count to choose next : m = 2
Output : 3

Input : n = 5
m=3
Output : 4

Answer
We have discussed different solutions of this problem (here and here). In this post a simple
circular linked list based solution is discussed.
1) Create a circular linked list of size n.
2) Traverse through linked list and one by one delete every m-th node until there is one node
left.
3) Return value of the only left node.

Question:
Given a singly linked list containing n nodes. Modify the value of first half nodes such that
1st node’s new value is equal to : current 1st node’ - the last node’s value
2nd node’s new value is equal to : current 2st node - the second last node’s value

, likewise for first half nodes.


If n is odd then the value of the middle node remains unchanged.
(No extra memory to be used).
Examples:

Input : 10 -> 4 -> 5 -> 3 -> 6


Output : 4 -> 1 -> 5 -> 3 -> 6

Input : 2 -> 9 -> 8 -> 12 -> 7 -> 10


Output : -8 -> 2 -> -4 -> 12 -> 7 -> 10

Answer
1. Split the list from the middle. If the number of elements is odd, the extra element
should go in the 1st(front) list.
2. Reverse the 2nd(back) list.
3. Perfrom the required subtraction while traversing both list simultaneously.
4. Again reverse the 2nd list.
5. Concatenate the 2nd list back to the end of the 1st list.

Question:
Partitioning a linked list around a given value {X} and keeping the original order
Input : 1->4->3->2->5->2->3, Input : 1->4->2->10
x = 3 x = 3
Output: 1->2->2->3->3->4->5 Output: 1->2->4->10

Answer

3 list , that will be merged in the end

Question:
Given a list of integers, rearrange the list such that it consists of alternating minimum
maximum elements using only list operations. The first element of the list should be
minimum and second element should be maximum of all elements present in the list.
Similarly, third element will be next minimum element and fourth element is next maximum
element and so on. Use of extra space is not permitted.
Examples:

Input: [1 3 8 2 7 5 6 4]
Output: [1 8 2 7 3 6 4 5]

Answer
The idea is to sort the list in ascending order first. Then we start popping elements from the
end of the list and insert them into their correct position in the list.

Question:
Flattening a Linked List
Given a linked list where every node represents a linked list and contains two pointers of its
type:
(i) Pointer to next node in the main list (we call it ‘right’ pointer in below code)
(ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer).

All linked lists are sorted. See the following example

5 -> 10 -> 19 -> 28


| | | |
V V V V
7 20 22 35
| | |
V V V
8 50 40
| |
V V
30 4

Write a function flatten() to flatten the lists into a single linked list. The flattened linked list
should also be sorted.

Answer
The idea is to use Merge() process of merge sort for linked lists. We use merge() to merge
lists one by one. We recursively merge() the current list with already flattened list.
The down pointer is used to link nodes of the flattened list.

Question:
Given a singly linked list of characters, write a function that returns true if the given list is
palindrome, else false.

Answer
A simple solution is to use a stack of list nodes.
1) Traverse the given list from head to tail and push every visited node to stack.
2) Traverse the list again. For every visited node, pop a node from stack and compare data
of popped node with currently visited node.

METHOD 2 (By reversing the list)

This method takes O(n) time and O(1) extra space.


1) Get the middle of the linked list.
2) Reverse the second half of the linked list.
3) Check if the first half and second half are identical.

When number of nodes are even, the first and second half contain exactly half nodes. The
challenging thing in this method is to handle the case when number of nodes are odd. We
don’t want the middle node as part of any of the lists as we are going to compare them for
equality. For odd case, we use a separate variable ‘midnode’.

Question:
Delete last occurrence of an item from linked list
Given a liked list and a key to be deleted. Delete last occurrence of key from linked. The list
may have duplicates.
Input: 1->2->3->5->2->10, key = 2
Output: 1->2->3->5->10

Answer
The idea is to traverse the linked list from beginning to end. While traversing, keep track
of last occurrence key. After traversing the complete list, delete last occurrence by
copying data of next node and deleting the next node.

You might also like