Linked List based problems
Last Lecture’s Problem 4
• Q4: Given two arrays each containing n sorted elements. Find
median of 2n elements in log n time complexity?
• Point to note: Both lists are already sorted. Can we use that ?
Obvious aim is to reduce searching-area-size during recursive call
to approx half.
• Find median of A and find median of B
• If (medianA == medianB) {ans =(medianA+medianB)/2; over}
• else if (medianA < medianB)
• { A[1.. (midA/2 -1)] and B[(midB/2 -1)..n] can be excluded;
half elements excluded:- log n should come
ans = median of X union Y,
where X is right sublist of A and Y is left sublist of B
}
2
Linked Lists
• Memory efficient DLL
• Instead of storing front & back pointers, can we do better?
• Store pointer difference calculated using XOR
3
Linked Lists: Cycle in a Singly LL
• Check whether a singly LL has a cycle or not?
• Sol A: Brute Force: pointer addresses comparison O(n2)
• Sol B: hashing
• Sol C: Memoryless & efficient solution in O (n): Floyd Algo
• Floyd Cycle Finding Algo: Hare and tortoise race in a track having
cycle.
4
5
Linked List : Interview Questions
• Q1: Find middle of a single LL
• Sol A: Use hash table: O (n)
• Sol B:
concept of Floyd cycle algo?
Use two pointers, one moves at the double speed of
other
6
Linked List : Interview Questions
• Q 2: Find nth node from the last in one scan
• Maintain two pointers;
one pointer always remains n-1 nodes before second
pointer;
7
Next Class Questions
• Check if a singly LL is palindrome or not?
• Generate clone of a singly LL, each node also having a
pointer to a random node in the LL.