706071. Triplets in Sorted Linked List

Medium

Count Triplets

Summary

This problem involves counting triplets in a sorted linked list. The triplets are formed by considering every three consecutive nodes and checking if they form an arithmetic progression (AP). The input is a linked list where each node contains an integer value, and the output is the count of all possible triplets that can be formed from these values.

Detailed Explanation

The algorithm to solve this problem involves iterating over the linked list and considering every three consecutive nodes as potential triplets. For each triplet, check if it forms an AP by verifying if the difference between the first two elements and the last element is the same.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable count to store the count of triplets.
  2. Iterate over the linked list using a pointer p.
  3. For each node, consider the next two nodes as a potential triplet (p, p->next, and p->next->next).
  4. Check if the difference between the first two elements (p->data and p->next->data) is equal to the difference between the last element (p->next->next->data) and the middle element (p->next->data). If it is, increment the count.
  5. Repeat steps 3-4 until the end of the linked list.
  6. Return the count as the final output.

Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we only use a constant amount of space to store the count and pointers.

Optimized Solutions

Java

View on GeeksforGeeks
public int countTriplets(Node head) {
    int count = 0;
    Node p = head;
    while (p != null && p.next != null && p.next.next != null) {
        if ((p.data - p.next.data) == (p.next.data - p.next.next.data)) {
            count++;
        }
        p = p.next.next;
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.