Open In App

Replace every node in a linked list with its closest triangular number

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list, the task is to replace every node with its closest triangular number.

Examples:

Input: 3 -> 9 -> 21 -> 25 -> NULL
Output: 3 -> 10 -> 21 -> 28 -> NULL
Explanation: The closest Triangular numbers for each node are:

  • Node 1 (value = 3): Closest Triangular number = 3.
  • Node 2 (value = 9): Closest Triangular number = 10.
  • Node 3 (value = 21): Closest Triangular number = 21.
  • Node 4 (value = 25): Closest Triangular number = 28.

Input: 10 -> 15 -> 30 -> 40 -> 50 -> NULL
Output: 10 -> 15 -> 28-> 36 -> 45 -> NULL
Explanation: The closest Triangular numbers for each node are:

  • Node 1 (value = 10): Closest Triangular number = 10.
  • Node 2 (value = 15): Closest Triangular number = 15.
  • Node 3 (value = 30): Closest Triangular number = 28.
  • Node 4 (value = 40): Closest Triangular number = 36.
  • Node 5 (value = 50): Closest Triangular number = 45.

Approach: This can be solved with the following idea:

This approach uses the concept of triangular numbers to replace every node in a linked list with its closest triangular number. Triangular numbers are the numbers that can be represented in the form of a triangular grid of points, where each row contains one more point than the previous one. The nth triangular number is the sum of the first n natural numbers, i.e., T(n) = 1 + 2 + … + n = n(n+1)/2. To find the closest triangular number for a given integer, we first find the smallest triangular number that is greater than or equal to the given integer. We can use the formula for the nth triangular number to find this. If the difference between this triangular number and the given integer is less than the difference between the previous triangular number and the given integer, we choose this triangular number as the closest one. Otherwise, we choose the previous triangular number as the closest one. Using this approach, we iterate through the linked list and replace the value of each node with its closest triangular number. Finally, we return the head of the modified linked list and print it to verify the output.

Steps of the above approach:

  • Inside the closestTriangular() function initialize a variable ‘i’ to 1, which represents the index of the triangular number we will start with.
  • Use a while loop to iterate through each triangular number until we find the smallest triangular number that is greater than or equal to the input ‘n’. The formula for the nth triangular number is n*(n+1)/2.
  • Compute the two closest triangular numbers to ‘n’ by using the formula for the (i-1)th triangular number and the ith triangular number.
  • Determine which of the two closest triangular numbers is actually closer to the input ‘n’ using the absolute value function abs() and a conditional statement.
  • Return the closest triangular number.
  • Then inside the replaceWithClosestTriangular() function Initialize a pointer variable ‘curr’ to the head of the linked list.
  • Use a while loop to iterate through each node in the linked list.
  • Call the closest triangular () function for each node to find its closest triangular number.
  • Update the value of the current node with its closest triangular number.
  • Move to the next node in the linked list by updating the pointer variable ‘curr’ to point to the next node.
  • Return the head of the modified linked list.

Below is the implementation of the above approach:

C++




// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
 
// Definition for singly-linked list.
struct Node {
    int data;
    Node* next;
    Node(int x)
        : data(x), next(NULL)
    {
    }
};
 
// Function to find the closest triangular
// number for a given integer
int closestTriangular(int n)
{
    int i = 1;
    while (i * (i + 1) / 2 < n) {
        i++;
    }
    int tn1 = i * (i + 1) / 2;
    int tn2 = (i - 1) * i / 2;
    if (abs(tn1 - n) < abs(tn2 - n)) {
        return tn1;
    }
    else {
        return tn2;
    }
}
 
// Function to replace every node in a
// linked list with its closest
// triangular number
Node* replaceWithClosestTriangular(Node* head)
{
    Node* curr = head;
    while (curr) {
        int closest = closestTriangular(curr->data);
        curr->data = closest;
        curr = curr->next;
    }
    return head;
}
 
// Function to print the linked list
void printList(Node* head)
{
    Node* curr = head;
    while (curr) {
        cout << curr->data << " -> ";
        curr = curr->next;
    }
    cout << "NULL" << endl;
}
 
// Driver code
int main()
{
 
    Node* head = new Node(3);
    head->next = new Node(9);
    head->next->next = new Node(21);
    head->next->next->next = new Node(25);
 
    // Function call
    head = replaceWithClosestTriangular(head);
    printList(head);
 
    return 0;
}


Java




// Java Implementation
class Node {
    int data;
    Node next;
 
    Node(int x) {
        data = x;
        next = null;
    }
}
 
public class ClosestTriangularNumber {
    // Function to find the closest triangular
    // number for a given integer
    static int closestTriangular(int n) {
        int i = 1;
        while (i * (i + 1) / 2 < n) {
            i++;
        }
        int tn1 = i * (i + 1) / 2;
        int tn2 = (i - 1) * i / 2;
        if (Math.abs(tn1 - n) < Math.abs(tn2 - n)) {
            return tn1;
        } else {
            return tn2;
        }
    }
 
    // Function to replace every node in a
    // linked list with its closest
    // triangular number
    static Node replaceWithClosestTriangular(Node head) {
        Node curr = head;
        while (curr != null) {
            int closest = closestTriangular(curr.data);
            curr.data = closest;
            curr = curr.next;
        }
        return head;
    }
 
    // Function to print the linked list
    static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " -> ");
            curr = curr.next;
        }
        System.out.println("NULL");
    }
 
    // Driver code
    public static void main(String[] args) {
        Node head = new Node(3);
        head.next = new Node(9);
        head.next.next = new Node(21);
        head.next.next.next = new Node(25);
 
        // Function call
        head = replaceWithClosestTriangular(head);
        printList(head);
    }
}
// This code is contributed by codearcade


Python3




# Definition for singly-linked list.
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
 
# Function to find the closest triangular number for a given integer
def closestTriangular(n):
    i = 1
    while i * (i + 1) // 2 < n:
        i += 1
    tn1 = i * (i + 1) // 2
    tn2 = (i - 1) * i // 2
    if abs(tn1 - n) < abs(tn2 - n):
        return tn1
    else:
        return tn2
 
 
# Function to replace every node in a linked list with its closest triangular number
def replaceWithClosestTriangular(head):
    curr = head
    while curr:
        closest = closestTriangular(curr.data)
        curr.data = closest
        curr = curr.next
    return head
 
 
# Function to print the linked list
def printList(head):
    curr = head
    while curr:
        print(curr.data, "-> ", end="")
        curr = curr.next
    print("NULL")
 
 
# Driver code
if __name__ == "__main__":
    head = Node(3)
    head.next = Node(9)
    head.next.next = Node(21)
    head.next.next.next = Node(25)
 
    # Function call
    head = replaceWithClosestTriangular(head)
    printList(head)


C#




using System;
 
// Definition for singly-linked list.
public class Node
{
    public int data;
    public Node next;
    public Node(int x)
    {
        data = x;
        next = null;
    }
}
 
public class GFG
{
    // Function to find the closest triangular
    // number for a given integer
    public static int ClosestTriangular(int n)
    {
        int i = 1;
        while (i * (i + 1) / 2 < n)
        {
            i++;
        }
        int tn1 = i * (i + 1) / 2;
        int tn2 = (i - 1) * i / 2;
        if (Math.Abs(tn1 - n) < Math.Abs(tn2 - n))
        {
            return tn1;
        }
        else
        {
            return tn2;
        }
    }
 
    // Function to replace every node in a
    // linked list with its closest
    // triangular number
    public static Node ReplaceWithClosestTriangular(Node head)
    {
        Node curr = head;
        while (curr != null)
        {
            int closest = ClosestTriangular(curr.data);
            curr.data = closest;
            curr = curr.next;
        }
        return head;
    }
 
    // Function to print the linked list
    public static void PrintList(Node head)
    {
        Node curr = head;
        while (curr != null)
        {
            Console.Write(curr.data + " -> ");
            curr = curr.next;
        }
        Console.WriteLine("NULL");
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        Node head = new Node(3);
        head.next = new Node(9);
        head.next.next = new Node(21);
        head.next.next.next = new Node(25);
 
        // Function call
        head = ReplaceWithClosestTriangular(head);
        PrintList(head);
    }
}


Javascript




// JavaScript Implementation
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}
 
function closestTriangular(n) {
    let i = 1;
    while (i * (i + 1) / 2 < n) {
        i++;
    }
    const tn1 = i * (i + 1) / 2;
    const tn2 = (i - 1) * i / 2;
    return Math.abs(tn1 - n) < Math.abs(tn2 - n) ? tn1 : tn2;
}
 
function replaceWithClosestTriangular(head) {
    let curr = head;
    while (curr !== null) {
        const closest = closestTriangular(curr.data);
        curr.data = closest;
        curr = curr.next;
    }
    return head;
}
 
function printList(head) {
    let curr = head;
    while (curr !== null) {
        console.log(curr.data + " -> ");
        curr = curr.next;
    }
    console.log("NULL");
}
 
// Driver code
    const head = new Node(3);
    head.next = new Node(9);
    head.next.next = new Node(21);
    head.next.next.next = new Node(25);
 
    // Function call
    replaceWithClosestTriangular(head);
    printList(head);


Output

3 -> 10 -> 21 -> 28 -> NULL








Time Complexity: O(n + sqrt(n))
Auxiliary Space: O(1), since we are not using any extra space.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads