Absolute difference of all pairwise consecutive elements in a Set
Last Updated :
28 Dec, 2021
Given a set of integers of N elements. The task is to print the absolute difference of all of the pairwise consecutive elements in a set. Pairwise consecutive pairs of a set of size N are accessed using iterator.
Example:
Input: s = {8, 5, 4, 3, 15, 20}
Output: 1 1 3 7 5
Explanation:
The set is : 3 4 5 8 15 20
The difference between 4 and 3 is 1
The difference between 5 and 4 is 1
The difference between 8 and 5 is 3
The difference between 15 and 8 is 7
The difference between 20 and 15 is 5
Input: s = {5, 10, 15, 20}
Output: 5 5 5
Explanation:
The set is : 5 10 15 20
The difference between 10 and 5 is 5
The difference between 15 and 10 is 5
The difference between 20 and 15 is 5
The article Absolute Difference of all pairwise consecutive elements in an array covers the approach to find the absolute difference of all pairwise consecutive elements in an array.
Approach: This problem can be solved using two pointer algorithm. We will be using iterators as the two pointers to iterate the set and check for a given condition. Follow the steps below to understand the solution to the above problem:
- Declare two iterators itr1 and itr2 and both of them point to the beginning element of the set.
- Increment itr2 i.e. itr2++ at the beginning of the loop.
- Subtract values pointed by itr1 and itr2 i.e. *itr2 - *itr1.
- Increment itr1 at the end of the loop, this means *itr1++.
- If itr2 reaches the end of the set, then break the loop and exit.
In C++, the set elements are sorted and duplicates are removed before storing in the memory. Therefore, in the below C++ program the difference between the pairwise consecutive elements is computed on the sorted set as explained in the above examples.
Below is the C++ program implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the
// difference of consecutive pairwise
// elements in a set
void display_difference(set<int> s)
{
// Declaring the set iterator
set<int>::iterator itr;
// Printing difference between
// consecutive elements in a set
set<int>::iterator itr1 = s.begin();
set<int>::iterator itr2 = s.begin();
while (1) {
itr2++;
if (itr2 == s.end())
break;
cout << (*itr2 - *itr1) << " ";
itr1++;
}
}
// Driver code
int main()
{
// Declaring the set
set<int> s{ 8, 5, 4, 3, 15, 20 };
// Invoking the display_difference()
// function
display_difference(s);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.TreeSet;
// Function to calculate the
// difference of consecutive pairwise
// elements in a set
class GFG {
static void display_difference(HashSet<Integer> S) {
// Printing difference between
// consecutive elements in a set
TreeSet<Integer> s = new TreeSet<Integer>(S);
int itr1 = 0;
int itr2 = 0;
while (true) {
itr2 += 1;
;
if (itr2 >= s.size()) {
break;
}
List<Integer> temp = new ArrayList<Integer>();
temp.addAll(s);
System.out.print((temp.get(itr2) - temp.get(itr1)) + " ");
itr1 += 1;
}
}
// Driver code
public static void main(String args[])
{
// Declaring the set
HashSet<Integer> s = new HashSet<Integer>();
s.add(8);
s.add(5);
s.add(4);
s.add(3);
s.add(15);
s.add(20);
// Invoking the display_difference()
// function
display_difference(s);
}
}
// This code is contributed by gfgking
Python3
# Python 3 program to implement
# the above approach
# Function to calculate the
# difference of consecutive pairwise
# elements in a set
def display_difference(s):
# Printing difference between
# consecutive elements in a set
itr1 = 0
itr2 = 0
while (1):
itr2 += 1
if (itr2 >= len(s)):
break
print((list(s)[itr2] - list(s)[itr1]), end=" ")
itr1 += 1
# Driver code
if __name__ == "__main__":
# Declaring the set
s = set([8, 5, 4, 3, 15, 20])
# Invoking the display_difference()
# function
display_difference(s)
# This code is contributed by ukasp.
C#
// C# program to implement
// the above approach
// Function to calculate the
// difference of consecutive pairwise
// elements in a set
using System;
using System.Collections.Generic;
public class GFG
{
static void display_difference(HashSet<int> S)
{
// Printing difference between
// consecutive elements in a set
SortedSet<int> s = new SortedSet<int>(S);
int itr1 = 0;
int itr2 = 0;
while (true) {
itr2 += 1;
;
if (itr2 >= s.Count) {
break;
}
List<int> temp = new List<int>();
temp.AddRange(s);
Console.Write((temp[itr2] - temp[itr1]) + " ");
itr1 += 1;
}
}
// Driver code
public static void Main(String []args)
{
// Declaring the set
HashSet<int> s = new HashSet<int>();
s.Add(8);
s.Add(5);
s.Add(4);
s.Add(3);
s.Add(15);
s.Add(20);
// Invoking the display_difference()
// function
display_difference(s);
}
}
// This code is contributed by Rajput-Ji.
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to calculate the
// difference of consecutive pairwise
// elements in a set
function display_difference(s) {
// Printing difference between
// consecutive elements in a set
s = new Set([...s].sort((a, b) => a - b));
let itr1 = 0
let itr2 = 0
while (1) {
itr2 += 1
if (itr2 >= s.size) {
break
}
document.write(([...s][itr2] - [...s][itr1]) + " ")
itr1 += 1
}
}
// Driver code
// Declaring the set
let s = new Set([8, 5, 4, 3, 15, 20]);
// Invoking the display_difference()
// function
display_difference(s)
// This code is contributed by Saurabh Jaiswal
</script>
Output:
1 1 3 7 5
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read