Asked inNagarro,SDE
Sort A “K” Sorted Doubly Linked List

You’re given a doubly-linked list with N nodes, where each node deviates at max K position from its position in the sorted list. Your task is to sort this given doubly linked list.

For example :
Let us consider K is 3, an element at position 4 in the sorted doubly linked list, can be at positions 1, 2, 3, 4, 5, 6, 7 in the given linked list because the absolute difference of all these indices with 4 is at most 3.
Note :
All elements are distinct.

A doubly linked list is a type of linked list that is bidirectional, that is, it can be traversed in both directions, forward and backward. 
Input Format :
The first line of input contains T, the number of test cases.

The first line of each test case contains an integer K, as specified in the problem statement.

The second line contains the elements of the doubly linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.
Output Format :
For each test case print in a new line the sorted linked list, the elements of the sorted list should be single-space separated, terminated by -1.  
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10000
1 <= K < N

Time Limit: 1 sec
CodingNinjas
author
2y

Sort the given doubly linked list using the insertion sort technique. While inserting each element in the sorted part of the list, there will be at most k swaps to place the element to its correct pos...read more

CodingNinjas
author
2y
Insertion Sort Approach

We will use Insertion sort to sort the doubly linked list efficiently.

Iterate the given doubly linked list head till the last node n, where n is the size of the doubly linked ...read more

CodingNinjas
author
2y
Min Heap Approach
  • We will start by creating a Min Heap(or a priority queue) of size k+1 with the data of the first k+1 nodes. Also make two pointers named next and prev, where prev points to the previo...read more
Add answer anonymously...
Nagarro SDE Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter