# Trending February 2024 # Javascript Program For Finding The Length Of Loop In Linked List # Suggested March 2024 # Top 4 Popular

You are reading the article Javascript Program For Finding The Length Of Loop In Linked List updated in February 2024 on the website Achiashop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Javascript Program For Finding The Length Of Loop In Linked List

In this program, we will be given a linked list that may consist of a loop and we have to find if the loop exists then what will be the size of the loop. Let’s a very famous approach to finding the length of a loop with the help of a code and discuss its time and space complexity.

Introduction to Problem

In this problem, as we have seen above we are given a linked list that may or may not contain a loop in it and we have to find the length of the loop if it exits otherwise we have to return zero as there is no loop present. We will use the Floyd loop method to find the loop and then check its size. For example, if we are given a linked list as −

And there is a loop from the node containing 8 to the node containing 4, which means 8 is connected to 4 making the loop of length 5 and we have to detect it.

Approach

In this problem, we will use the Floyd loop method to detect the loop and then we will use the concept of length finding to find the length of the loop. Let’s first see the basic steps of the problem then we will move to Floyd’s method and length method.

First, we will create the class to provide the basic structure of the nodes of the linked list and define constructors in it to initialize the node values.

Then we created a function to push the elements in the given linked list.

We have created a linked list using the above method and then we have linked the last node to another node to make a cycle in it.

Floyd’s Algorithm

In this algorithm, we traverse over the linked list and once we have entered the linked list then we cannot go out from any node. This means if we have two pointers in that linked list loop part and one pointer is moving forward with one node at a time and another is at the pace of two nodes at a time, they will meet at a certain point.

After implementing the algorithm, we will call that function and check if the loop is present or not

If the loop is present than we will call to the anther function to find the length of the loop.

Another wise we will return and print no loop is present.

Example

In the below example, we define a linked list and add 8 nodes to it. We make loop in a linked list by connecting node 8 to node 4. So it makes a loop of five nodes.

In the above code, we have traversed over the complete linked list only once and for the loop part maximum of three times which makes the time complexity linear. So the time complexity of the above code is linear that is O(N) where N is the size of the linked list.

As we are not using any extra space makes the time complexity of the program O(1).

Conclusion

In this tutorial, we have learned how to find the length of the loop present in the linked list by implementing the concepts in the JavaScript language. We have used Floyd’s loop-finding algorithm to find the loop in the given linked list and then we have just used the while loop to traverse over the loop and find its length. The time complexity of the above code is O(N) and the space complexity is O(1).

You're reading Javascript Program For Finding The Length Of Loop In Linked List

## Javascript Program For Quicksort On Singly Linked List

The Singly-linked list is a linear data structure that consists of nodes. Each node contains the data and the pointer to the next node which contains the memory address of the next node because the memory assigned to each node is not continuous.

Sorting is a technique by which we make all the elements of a particular data structure such as a linked list, array, vector, etc in a properly sorted manner in either increasing or decreasing order (if not specified in increasing order). We will see the proper code and the explanation in this article.

Introduction to Problem

In this problem, we have to implement the quicksort algorithm on the singly linked list. QuickSort is a kind of sorting algorithm or technique that is implemented using recursion and has the best time complexity of O(N * log(N)).

Recursion is a prerequisite to the quicksort algorithm. Recursion is a programming pattern in which we define a function that will keep calling itself with the inputs (that are passed as the parameters) keep decreasing or increasing in value. There will be a base condition present by which the recursive calls end. Let’s see the steps to implement the quicksort algorithm before implementing it in the code format.

Approach

To implement the QuickSort on the singly-linked list we are going to follow these steps −

To get a pivot node at the proper position, we will use the partition function.

The last element in the partition function is marked as a the pivot.

Then we will traverse the current list and relocate any node with a value larger than the pivot after the tail. If the node has a lower value, it should remain in its present or the current place.

At the end we will return the node that is the pivot.

We will find the linked list’s tail node on the left side of the pivot and repeat for the left side of the linked list.

Similarly, following the left side, repeat for the linked list on the pivot’s node right side.

As the entire linked list is now sorted, return the head of the linked list after connecting the left and right linked lists.

The time complexity of the above code is not constant and totally depends upon the given input, but on an average the time complexity of the above code is O(N*log(N)) and this is also the best case of the current sorting algorithm. Worst case of the quicksort algorithm is O(N*N), which is in-effecitve.

The space complexity of the above code is O(N) due to the recursion stack.

Conclusion

In this tutorial, we have implemented a JavaScript program for quicksort on a singly linked list. The Singly-linked list is a linear data structure that consists of nodes. QuickSort is a kind of sorting algorithm or technique that is implemented using recursion and has the best and average time complexity of O(N * log(N)) and Recursion is a prerequisite to the quicksort algorithm. The worst case for the time complexity of the above code is O(N*N).

## Linked List For Dynamic Partitioning

A linked list is made up of nodes, each of which has a data element and a pointer (or reference) to the node after it in the list. Each node in dynamic partitioning represents a memory block that can be assigned to a process. The linked list initially reflects the whole memory block that is accessible. In this article, we will explore the Linked List for Dynamic Partitioning, what Dynamic Partitioning is in Memory Management, and also the implementation of Linked List in Dynamic Partitioning.

Dynamic Partitioning in Memory Management

Computer systems employ the memory management approach known as “dynamic partitioning,” which divides memory into segments of varying sizes to support numerous processes at once. Dynamic partitioning minimizes memory resource wastage by giving each process only the amount of memory it needs.

The following is how the dynamic partitioning method operates −

At first, the entire amount of memory that is accessible is thought of as a single huge block.

The system looks for a free block of memory that is big enough to hold the requested memory whenever a process requests memory. Different algorithms, including First Fit, Best Fit, and Worst Fit, might be used to do the search.

An appropriate block is then assigned to the requesting process after being discovered.

The remaining portion of the block is returned to the free memory pool if the allocated block is further than the needed quantum of memory.

The memory that was allocated is deallocated after a process completes, and the freed memory is returned to the free memory pool.

Fragmentation, or the division of memory into little free blocks that are worthless owing to their size, is a problem with the dynamic partitioning technique. Internal and external fragmentation are the two types of fragmentation.

When a memory block allotted to a process is greater than the memory that was requested, internal fragmentation results. In this scenario, the leftover chunk of the block is returned to the free memory pool, but because of its size, it cannot be used by other processes, resulting in memory waste.

It becomes challenging to allocate a larger block of memory to a process when there exist numerous tiny, non-contiguous free blocks of memory. This condition is known as external fragmentation. The solution to this problem is to combine nearby free memory blocks into a single, larger block, however doing so can be computationally expensive.

Dynamic partitioning is a flexible and effective memory management method that allocates only the necessary amount of RAM to each operation, minimizing memory resource waste. However, it has fragmentation problems that may affect the system’s performance.

Implementation of Linked List for Dynamic Partitioning

Making a data structure that can effectively allocate and deallocate memory blocks to processes is necessary for the creation of a linked list for dynamic partitioning. Here is an illustration of how to implement a linked list in C for dynamic partitioning −

typedef struct node { int size; int free; struct node* next; } Node; Node* head = NULL; void initialize(int size) { head = (Node*)malloc(sizeof(Node)); } void* allocate(int size) { Node* current = head; while (current != NULL) { Node* new_node = (Node*)((char*)current + sizeof(Node) + size); } else { } return (void*)((char*)current + sizeof(Node)); } } return NULL; } void deallocate(void* ptr) { Node* current = head; while (current != NULL) { if ((void*)((char*)current + sizeof(Node)) == ptr) { } Node* prev = head; } free(current); } break; } } }

Here, a memory block in a linked list is represented by a Node struct.

The size refers to the block’s size.

Free indicates if the block is free or allocated to a process.

Next is a pointer to the node after it in the list.

The allocate function allots memory to a process by looking for a free memory block that can handle the desired size. The initialize function initializes the linked list using the available memory size. The block is divided into two blocks if it is greater than the required size, with the second block being added to the linked list as a free block.

The deallocate function releases memory from a process. If possible, also merges nearby free memory blocks into a single, bigger block.

Conclusion

Computer systems can benefit from the usage of a linked list for dynamic partitioning. Converging nearby free memory blocks, enables effective allocation and deallocation of memory blocks to processes and helps lessen memory fragmentation. Making a data structure with a size, a flag to show whether the block is free or allocated, and a pointer to the subsequent node in the linked list is required to implement a linked list for dynamic partitioning. Memory can be allotted to processes by initializing the linked list with the amount of available memory and looking for free memory blocks that can support the requested size.

## Javascript Program For Equilibrium Index Of An Array

The position where the sum of the elements to its left and right equals one another is known as the equilibrium index of an array. To put it another way, if we take a look at an array of size n, the equilibrium index i is a point such that −

arr[0] + arr[1] + ... + arr[i-1] = arr[i+1] + arr[i+2] + ... + arr[n-1]

where i is the equilibrium index and arr is the input array. We may alternatively state that the array is divided into two parts by the equilibrium index i such that the total of the elements in the left and right sections are equal.

For Example −

Let’s consider the following array −

A = [2, 4, -3, 0, -4, 6, 1] In this sequence, the equilibrium index is 3 (element 0) because (2+4-3) = (-4+6+1). It is also balanced with another equilibrium index 5 (element 6) because (2+4-3+0-4) = (1). Problem Statement

Given an array of integers, find the index of the equilibrium point of the array. If there is no equilibrium point, return -1.

Example

Consider an array of integers −

[3, 7, 1, 5, 10, 2, 7, 9]

The equilibrium index of this array is 4 because the sum of elements before the index (3+7+1+5 = 16) is equal to the sum of elements after the index (2+7+9 = 18).

Method 1: Using the Loop

Use two loops: the outer loop iterates through all of the elements, while the inner loop determines whether or not the current index selected by the outer loop is an equilibrium index. The time complexity of this approach is O(n2), which will be explained later. The usage of two loops is simple. The goal is to find the sum of elements for each range of indexes and see if an equilibrium index exists. The outer loop traverses the array, while the inner loop assesses whether or not there is an equilibrium index.

Algorithm

Use two loops

Outer loop iterates through all the elements and the inner loop checks out whether the current index picked by the outer loop is either an equilibrium index or not.

Run a loop through the array

For each index, find the sum of elements towards the left and right of the current index

If the left_sum and right_sum are equal, then the current index is the equilibrium index

Otherwise, return -1

The time complexity of this solution is O(n2)

Example

const arr = [-7, 1, 5, 2, -4, 3, 0];

let equilibriumIndexFound = false;

for (let i = 0; i < arr.length; i++) { let leftSum = 0; let rightSum = 0;

for (let j = 0; j < i; j++) { leftSum += arr[j]; }

for (let j = i + 1; j < arr.length; j++) { rightSum += arr[j]; }

if (leftSum === rightSum) { document.body.innerHTML += `The equilibrium index of the array is \${i}`; equilibriumIndexFound = true; break; } }

if (!equilibriumIndexFound) { document.body.innerHTML += `There is no equilibrium index in the array`; }

Please keep in mind that the preceding code is only for demonstration purposes and should not be used in production because it is not optimised. It has an O(n2) time complexity, which is inefficient for big arrays.

Method 2: Prefix Sum

Another way to calculate an array’s equilibrium index is the prefix sum method. With this method, we first compute the array’s prefix sum, which is the sum of elements from the array’s beginning to the current index. Then, using the prefix sum, we loop through the array, checking if the total of elements to the left of the current index equals the sum of elements to the right of the current position.

Algorithm

Determine the array’s prefix sum.

Iterate through the array and use the prefix sum to see if the sum of items to the left of the current index equals the sum of elements to the right of the current position.

Return that index as the equilibrium index if the sum of the components to the left equals the sum of the elements to the right.

If no equilibrium index exists, return -1.

Example

function equilibriumIndex(arr) { let n = arr.length;

let prefixSum = []; prefixSum[0] = arr[0]; for (let i = 1; i < n; i++) { prefixSum[i] = prefixSum[i – 1] + arr[i]; }

for (let i = 0; i < n; i++) { let leftSum = (i == 0) ? 0 : prefixSum[i – 1]; let rightSum = prefixSum[n – 1] – prefixSum[i]; if (leftSum == rightSum) { return i; } }

return -1; } let arr = [-7, 1, 5, 2, -4, 3, 0];

let result = equilibriumIndex(arr); if (result == -1) { document.write(“No equilibrium index found”); } else { document.write(“Equilibrium index is ” + result); }

Note − The time complexity of the prefix sum approach to find the equilibrium index of an array is O(n), where n is the size of the array

Method 3: Two Pointers

In this method, we can keep track of two pointers, one at the start and one at the end of the array. With these two pointers, we can then calculate the left and right sums and shift the pointers towards each other until we obtain the equilibrium index.

Algorithm

Initialize leftSum and rightSum as 0 and n-1 as the right pointer.

Traverse the array from left to right.

At each element, add the element to the leftSum and subtract it from the rightSum.

If leftSum equals rightSum, return the current index as the equilibrium index.

If no equilibrium index is found, return -1.

Example

const arr = [-7, 1, 5, 2, -4, 3, 0]; const n = arr.length; let leftSum = 0; let rightSum = 0; document.getElementById(“input”).innerHTML = “Input Array: ” + arr.join(“, “); for (let i = 0; i < n; i++) { rightSum += arr[i]; } for (let i = 0; i < n; i++) { rightSum -= arr[i]; if (leftSum === rightSum) { document.getElementById(“output”).innerHTML = “Equilibrium index: ” + i; break; } leftSum += arr[i]; } if (document.getElementById(“output”).innerHTML === “”) { document.getElementById(“output”).innerHTML = “No equilibrium index found”; }

Note − The time complexity of the prefix sum approach to find the equilibrium index of an array is O(n), where n is the size of the array.

Conclusion

In this blog we have talked about finding the equilibrium index of an array by various methods. Some of them are using loop, prefix sum and two pointer approaches. Ho[e you found this information useful.

## Working Of Loop In Clojure

Introduction to Clojure loop

Clojure has a special kind of loop, unlike other programming languages, which sets a recursion point by making use of recur, meaning recur is always associated with loop. A loop is said to be completed when the number of arguments passed to the recur is the same as the number of bindings for the loop, ensuring that the recur is in sync with the loop. There is a base case associated with every recursive function based on which the looping stops, and by making use of the loop, we are implying the compiler to try its best to optimize the code for recursion.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

loop [binding] (condition (statement) (recur (binding)))

Binding is the number of bindings for the loop, which is the same as the recur function arguments.

Flowchart

Flowchart for the working of the loop in Clojure is as follows:

Working of the loop in Clojure

The loop begins with the binding variable followed by the evaluation of the condition.

If the condition is true, the control goes to statements specified inside the condition and executes them.

If the condition is false, the loop stops.

After the execution of statements inside the condition, the control again goes to the binding variable passed as a parameter to the recur function, completing a loop and continues the execution of the loop again.

The same procedure continues until the condition is false and the loop stops.

Examples of Clojure loop

Given below are the examples of Clojure loop:

Example #1

Clojure program to demonstrate a loop using recur function to print the numbers starting from 20 decremented by 1 in every step and display it as the output on the screen.

Code:

;; defining a function called decrement to decrease the values by 1 starting from 20 (defn decrement [] (loop [y 20] (println y) (recur (- y 1))))) (decrement)

Output:

In the above program, we are defining a function called decrement to decrease the given value by one after each iteration. The binding value to the loop is 20, which is decremented by 1 in the recur function and continues till the condition that the value of the variable y is greater than 0.

Example #2

Clojure program to demonstrate a loop using recur function to print the numbers starting from 0 incremented by 1 in every step and display it as the output on the screen.

Code:

;; defining a function called increment to increase the values by 1 starting from 0 to 20 (defn increment [] (loop [y 0] (when (< y 21) (println y) (recur (+ y 1))))) (increment)

Output:

In the above program, we are defining a function called increment to increase the given value by one after each iteration. The binding value to the loop is 0, which is incremented by 1 in the recur function and continues till the condition that the value of the variable y is lesser than 21.

Example #3

Clojure program to demonstrate a loop using recur function to print the numbers starting from 2 multiplied by 2 in every step whose result continues till the value of the variable is less than 21 and displays it as the output on the screen.

Code:

;; defining a function called multiply to multiply the given value by 2 starting from 2 till the result value becomes less than 21 (defn multiply [] (loop [y 2] (when (< y 21) (println y) (recur (* y 2))))) (multiply)

Output:

In the above program, we are defining a function called multiply to multiply the given value by two after each iteration. The binding value to the loop is 2, which is multiplied by 2 in the recur function and continues until the condition that the variable y becomes lesser than 21.

Example #4

Clojure program to demonstrate a loop using recur function to print the numbers starting from 20 divided by 2 in every step whose result continues till the value of the variable is less than 1 and displays it as the output on the screen.

;; defining a function called divide to divide the given value by 2 starting from 20 till the result value becomes less than 1 (defn divide [] (loop [y 20] (println y) (recur (/ y 2))))) (divide)

Output:

In the above program, we are defining a function called divide to divide the given value by two after each iteration. The binding value to the loop is 20, which is divided by 2 in the recur function and continues till the condition that the value of the variable y becomes lesser than 1.

Example #5

Clojure program to demonstrate a loop using recur function to print the numbers starting from 20 decremented by 5 in every step and display it as the output on the screen.

Code:

;; defining a function called decrement to decrease the values by 5 starting from 20 (defn decrement [] (loop [y 20] (println y) (recur (- y 5))))) (decrement)

Output:

In the above program, we are defining a function called decrement to decrease the given value by five after each iteration. The binding value to the loop is 20, which is decremented by 5 in the recur function and continues till the condition that the value of the variable y is greater than 0.

Recommended Articles

We hope that this EDUCBA information on “Clojure loop” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

## Javascript Program For Print All Triplets In Sorted Array That Form Ap

AP is the arithmetic progression in which the difference between two consecutive elements is always the same. We will print all the triplet in a sorted array that form AP using three approaches: Naive approach, binary search method and two-pointer approach.

Introduction to Problem

In this problem we are given by a sorted array meaning all the elements are in the increasing form. We have to find the three elements which are part of the array and form an AP. For example −

Given array: 1 5 2 4 3

From the given array we have two triplets: 1 2 3 and 5 4 3 as the difference between the adjacent elements is equal. Also, as it is written that we have to find the triplets only so we will not find any longer sequences.

Let us move to the approaches to find the triplets −

Approach Naive Approach

In this approach we are just moving over the array using a loop and for each iteration we will run another array for the numbers that are greater as compared to our current index. Then we will again implement a nested array inside the first nested array to find the element which can form AP. Let’s see the code −

Example function findAP(arr){ var n = arr.length for(var i = 0; i< n;i++){ for(var j = i+1;j<n;j++){ for(var k = j+1; k < n; k++){ if(arr[j] - arr[i] == arr[k] - arr[j]) { console.log("Triplet is: " + arr[i] + " " + arr[j] + " " + arr[k]); } } } } } arr = [1, 5, 2, 4, 3] findAP(arr)

The time complexity of the above code O(), where N is the size of the array.

The space complexity of the above code O(1), as we are not using any extra space.

In the previous approach, when we have two elements then we can find the third one as we have the common difference, so to find the third element instead of using linear search we can use the binary search and reduce the time complexity of the above code −

Example var binarySearch = function (arr, x, start, end) { var mid=Math.floor((start + end)/2); if (arr[mid]===x) return true; return binarySearch(arr, x, start, mid-1); else return binarySearch(arr, x, mid+1, end); } function findAP(arr){ var n = arr.length for(var i = 0; i< n;i++){ for(var j = i+1;j<n;j++){ var third = 2*arr[j]-arr[i]; if(binarySearch(arr,third,j+1,n)){ console.log("Triplet is: " + arr[i] + " " + arr[j] + " " + third); } } } } arr = [1, 5, 2, 4, 3] findAP(arr)

The time complexity of the above code O(), where N is the size of the array.

The space complexity of the above code O(1), as we are not using any extra space.

Efficient Approach

In this approach we are going to use two pointers and find the elements which are at the same difference from the current position. Let us see the code −

Example function findAP(arr){ var n = arr.length for(var i = 1; i< n;i++) { var bptr = i-1 var fptr = i+1 if(arr[i] - arr[bptr] == arr[fptr] - arr[i]){ console.log("Triplet is: " + arr[bptr] + " " + arr[i] + " " + arr[fptr]); bptr--; fptr++; } fptr++; } else{ bptr--; } } } } arr = [1, 4, 7, 10, 13, 16] findAP(arr)

The time complexity of the above code is O(N*N) where N is the size of the given array and space complexity of the above approach is the O(1) as we are not using any extra space.

Note − First two methods are efficient for any type of array that is sorted or unsorted, but the last method is only applicable for the sorted arrays and if the array is not sorted we can make it one and still this method will be best among all others.

Conclusion

In this tutorial, we have implemented a JavaScript program to print all the triplets in a given sorted array that form an AP. Ap is the arithmetic progression in which the difference between two consecutive elements is always the same. We have seen three approaches: Naive approach with O(N*N*N) time complexity, binary search method with O(N*N*log(N)) time complexity, and two pointer approach.

Update the detailed information about Javascript Program For Finding The Length Of Loop In Linked List on the Achiashop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!