Create a new linked list from maximum square differences
Last Updated :
11 Sep, 2024
Given a linked list with an even number of nodes, the task is to generate a new linked list that contains the maximum difference of squares of node values, arranged in decreasing order. Each node should be included in exactly one pair.
Examples:
Input: 1 -> 6 -> 4 -> 3 -> 5 ->2
Output: 35 -> 21 -> 7
Explanation:
- The difference between squares of 6 and 1 forms the first node with value 35.
- The difference between squares of 5 and 2 forms the second node with value 21.
- The difference between squares of 4 and 3 forms the third node with value 7.
- Therefore, the formed Linked list is 35 -> 21 -> 7.
Input: 2 -> 4 -> 5 -> 3 -> 7 -> 8 -> 9 -> 10
Output: 96 -> 72 -> 48 -> 24
Explanation:
- The difference between squares of 10 and 2 forms the first node with value 96.
- The difference between squares of 9 and 3 forms the second node with value 72.
- The difference between squares of 8 and 4 forms the third node with value 48.
- The difference between squares of 7 and 5 forms the fourth node with value 24.
- Therefore, the formed Linked list is 96 -> 72 -> 48 -> 24.
Approach:
First, we take all the node values into an array and sort this array in increasing order for accessing the smallest and largest values easily.
We then use two pointers: one starting at the beginning of the sorted array (pointing to the smallest value) and the other at the end (pointing to the largest value).
By pairing the largest with smallest value, we calculate the difference of their squares, which resulting in the maximum possible difference for that pair. Then create a new node with this difference value and append it to the new linked list. We continue this process for the second largest and second smallest values and so on until no pairs remain.
Step-by-step approach:
- Traverse list and store values in an array.
- Sort the vector.
- Initialize two pointers (left, right).
- While left < right, calculate square differences.
- Create new nodes for differences and append to result list.
- Return the head of the new list.
Below is the implementation of the above approach:
C+
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to create a new linked list
// from maximum square differences
Node* maxDiffList(Node* head) {
vector<int> arr;
// Insert all node values into the array
Node* curr = head;
while (curr != nullptr) {
arr.push_back(curr->data);
curr = curr->next;
}
// Sort the array
sort(arr.begin(), arr.end());
// Create a new linked list for the result
Node* resHead = nullptr;
Node* tail = nullptr;
// Two pointers, one at the start and one
// at the end of the array
int left = 0;
int right = arr.size() - 1;
// Loop while there are at least two elements
while (left < right) {
// Get largest and minn values
int maxVal = arr[right];
int minVal = arr[left];
// Calculate the difference of squares
int diff = maxVal*maxVal - minVal*minVal;
// Create a new node with the calculated
// difference
Node* newNode = new Node(diff);
// Add the new node to the result linked list
if (resHead == nullptr) {
resHead = newNode;
} else {
tail->next = newNode;
}
tail = newNode;
// Move the pointers inward
left++;
right--;
}
return resHead;
}
void printList(Node* head) {
Node* curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
// Create the initial linked list:
// 1 -> 6 -> 4 -> 3 -> 5 -> 2
Node* head = new Node(1);
head->next = new Node(6);
head->next->next = new Node(4);
head->next->next->next = new Node(3);
head->next->next->next->next = new Node(5);
head->next->next->next->next->next =
new Node(2);
Node* resHead = maxDiffList(head);
printList(resHead);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int x);
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
// Function to create a new linked list
// from maximum square differences
struct Node* maxDiffList(struct Node* head) {
int arr[10000];
int size = 0;
// Insert all node values into the array
struct Node* curr = head;
while (curr != NULL) {
arr[size++] = curr->data;
curr = curr->next;
}
// Sort the array
qsort(arr, size, sizeof(int), compare);
// Create a new linked list for the result
struct Node* resHead = NULL;
struct Node* tail = NULL;
// Two pointers, one at the start and one
// at the end of the array
int left = 0;
int right = size - 1;
// Loop while there are at least two elements
while (left < right) {
// Get largest and smallest values
int maxVal = arr[right];
int minval = arr[left];
// Calculate the difference of squares
int diff = maxVal * maxVal - minval
* minval;
// Create a new node with the calculated
// difference
struct Node* newNode = createNode(diff);
// Add new node to the result linked list
if (resHead == NULL) {
resHead = newNode;
} else {
tail->next = newNode;
}
tail = newNode;
// Move the pointers inward
left++;
right--;
}
return resHead;
}
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
struct Node* createNode(int x) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = NULL;
return newNode;
}
int main() {
// Create the initial linked list:
// 1 -> 6 -> 4 -> 3 -> 5 -> 2
struct Node* head = createNode(1);
head->next = createNode(6);
head->next->next = createNode(4);
head->next->next->next = createNode(3);
head->next->next->next->next = createNode(5);
head->next->next->next->next->next =
createNode(2);
struct Node* resHead = maxDiffList(head);
printList(resHead);
return 0;
}
Java
import java.util.*;
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to create a new linked list
// from maximum square differences
static Node maxDiffList(Node head) {
List<Integer> arr = new ArrayList<>();
// Insert all node values into the array
Node curr = head;
while (curr != null) {
arr.add(curr.data);
curr = curr.next;
}
// Sort the array
Collections.sort(arr);
// Create a new linked list for the result
Node resHead = null;
Node tail = null;
// Two pointers, one at the start and one
// at the end of the array
int left = 0;
int right = arr.size() - 1;
// Loop while there are at least two elements
while (left < right) {
// Get largest and smallest values
int maxVal = arr.get(right);
int minVal = arr.get(left);
// Calculate the difference of squares
int diff = maxVal*maxVal - minVal*minVal;
// Create a new node with the calculated
// difference
Node newNode = new Node(diff);
// Add the new node to the result linked list
if (resHead == null) {
resHead = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
// Move the pointers inward
left++;
right--;
}
return resHead;
}
static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create the initial linked list:
// 1 -> 6 -> 4 -> 3 -> 5 -> 2
Node head = new Node(1);
head.next = new Node(6);
head.next.next = new Node(4);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(2);
Node resHead = maxDiffList(head);
printList(resHead);
}
}
Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to create a new linked list
# from maximum square differences
def maxDiffList(head):
arr = []
# Insert all node values into the array
curr = head
while curr is not None:
arr.append(curr.data)
curr = curr.next
# Sort the array
arr.sort()
# Create a new linked list for the result
resHead = None
tail = None
# Two pointers, one at the start and one
# at the end of the array
left = 0
right = len(arr) - 1
# Loop while there are at least two elements
while left < right:
# Get largest and smallest values
maxVal = arr[right]
minHVal = arr[left]
# Calculate the difference of squares
diff = maxVal*maxVal - minHVal*minHVal
# Create a new node with the calculated
# difference
newNode = Node(diff)
# Add the new node to the result linked list
if resHead is None:
resHead = newNode
else:
tail.next = newNode
tail = newNode
# Move the pointers inward
left += 1
right -= 1
return resHead
def printList(head):
curr = head
while curr is not None:
print(curr.data, end=" ")
curr = curr.next
print()
if __name__ == "__main__":
# Create the initial linked list:
# 1 -> 6 -> 4 -> 3 -> 5 -> 2
head = Node(1)
head.next = Node(6)
head.next.next = Node(4)
head.next.next.next = Node(3)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(2)
resHead = maxDiffList(head)
printList(resHead)
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node next;
public Node(int x)
{
data = x;
next = null;
}
}
class GFG {
// Function to create a new linked list
// from maximum square differences
static Node maxDiffList(Node head){
List<int> arr = new List<int>();
// Insert all node values into the array
Node curr = head;
while (curr != null) {
arr.Add(curr.data);
curr = curr.next;
}
// Sort the array
arr.Sort();
// Create a new linked list for the result
Node resHead = null;
Node tail = null;
// Two pointers, one at the start and one
// at the end of the array
int left = 0;
int right = arr.Count - 1;
// Loop while there are at least
// two elements
while (left < right) {
// Get largest and smallest values
int maxVal = arr[right];
int minVal = arr[left];
// Calculate the difference of squares
int diff = maxVal*maxVal
- minVal*minVal;
// Create a new node with the calculated
// difference
Node newNode = new Node(diff);
// Add the new node to the result linked list
if (resHead == null) {
resHead = newNode;
}
else {
tail.next = newNode;
}
tail = newNode;
// Move the pointers inward
left++;
right--;
}
return resHead;
}
static void printList(Node head){
Node curr = head;
while (curr != null) {
Console.Write(curr.data + " ");
curr = curr.next;
}
Console.WriteLine();
}
public static void Main(string[] args){
// Create the initial linked list:
// 1 -> 6 -> 4 -> 3 -> 5 -> 2
Node head = new Node(1);
head.next = new Node(6);
head.next.next = new Node(4);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(2);
Node resHead = maxDiffList(head);
printList(resHead);
}
}
JavaScript
class Node {
constructor(data)
{
this.data = data;
this.next = null;
}
}
// Function to create a new linked list
// from maximum square differences
function maxDiffList(head){
let arr = [];
// Insert all node values into the array
let curr = head;
while (curr !== null) {
arr.push(curr.data);
curr = curr.next;
}
// Sort the array
arr.sort((a, b) => a - b);
// Create a new linked list for the result
let resHead = null;
let tail = null;
// Two pointers, one at the start and one
// at the end of at the end of the array
let left = 0;
let right = arr.length - 1;
// Loop while there are at least two elements
while (left < right) {
// Get largest and smallest values
let maxVal = arr[right];
let minVal = arr[left];
// Calculate the difference of squares
let diff = maxVal*maxVal - minVal*minVal;
// Create a new node with the calculated
// difference
let newNode = new Node(diff);
// Add the new node to the result
// linked list
if (resHead === null) {
resHead = newNode;
}
else {
tail.next = newNode;
}
tail = newNode;
// Move the pointers inward
left++;
right--;
}
return resHead;
}
function printList(head){
let curr = head;
while (curr !== null) {
console.log(curr.data);
curr = curr.next;
}
console.log();
}
// Create the initial linked list:
// 1 -> 6 -> 4 -> 3 -> 5 -> 2
let head = new Node(1);
head.next = new Node(6);
head.next.next = new Node(4);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(2);
let resHead = maxDiffList(head);
printList(resHead);
Time Complexity: O(n*log n), for sorting.
Auxiliary Space: O(n)
Similar Reads
Maximum adjacent difference in an array in its sorted form Given an array arr[] of size N, find the maximum difference between its two consecutive elements in its sorted form. Examples: Input: N = 3, arr[] = {1, 10, 5}Output: 5Explanation: Sorted array would be {1, 5, 10} and maximum adjacent difference would be 10 - 5 = 5 Input: N = 4, arr[] = {2, 4, 8, 11
8 min read
Find maximum absolute difference between weights of adjacent nodes in Linked list Given a linked list with weights, the task is to find the maximum absolute difference between any two weights of nodes that are adjacent in the list. Examples: Input: 2 (4) -> 5 (8) -> 6 (1) -> 4 (3) -> 7 (2) -> NULLOutput: 7Explanation: The maximum absolute difference between any two
10 min read
Maximum sum of K consecutive nodes in the given Linked List Given a linked list, the task is to find the maximum sum obtained by adding any k consecutive nodes of linked list. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, K = 5 Output: 20 Maximum sum is obtained by adding last 5 nodes Input: 2 -> 5 -> 3 -> 6 -> 4 -> 1
8 min read
Maximum distance between Peaks in given Linked List Given a linked list of length n, the task is to determine the maximum distance between two consecutive peaks of the given linked list. A peak is a node with a value greater than its neighbours. The distance between two nodes is defined as the number of nodes present between them. Examples:Input: Lin
11 min read
Maximum sum contiguous nodes in the given linked list Given a linked list, the task is to find the maximum sum for any contiguous nodes. Examples: Input: -2 -> -3 -> 4 -> -1 -> -2 -> 1 -> 5 -> -3 -> NULL Output: 7 4 -> -1 -> -2 -> 1 -> 5 is the sub-list with the given sum. Input: 1 -> 2 -> 3 -> 4 -> NULL
11 min read